webapi_uploadfile_gdal_to_geojson_and_unzipfile
using ICSharpCode.SharpZipLib.Zip;
using OSGeo.GDAL;
using OSGeo.OGR;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc; namespace gdal_to_geojson_service.Controllers
{
public class GeojsonController : ApiController
{ public string Post()
{
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); string root = HttpContext.Current.Server.MapPath("/UploadFiles/");
if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadFiles/")))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadFiles/"));
}
try
{
HttpPostedFile file = HttpContext.Current.Request.Files[];
string tempfilename = Guid.NewGuid().ToString();
string path = Path.Combine(root, tempfilename + ".zip");
file.SaveAs(path);
ExtractZipFileToFolder(path, Path.Combine(root, tempfilename));
string[] files = Directory.GetFiles(Path.Combine(root, tempfilename), "*.shp");
if (files.Length > )
{
return ConvertJson(files[], Path.Combine(root, tempfilename + ".json"));
}
}
catch (Exception ex)
{
return "Error" + Environment.NewLine + ex.Message;
}
return "Error";
} private string ConvertJson(string shpFilePath, string jsonFile)
{
if (!File.Exists(shpFilePath))
{ throw new FileNotFoundException(".shp文件不存在"); } Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
Gdal.SetConfigOption("SHAPE_ENCODING", "");
Ogr.RegisterAll();// 注册所有的驱动
OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
if (dr == null)
{
throw new Exception("文件不能打开,请检查");
}
OSGeo.OGR.DataSource ds = dr.Open(shpFilePath, ); using (OSGeo.OGR.Driver dv = OSGeo.OGR.Ogr.GetDriverByName("GeoJSON"))
{
if (dv == null)
{
throw new Exception("打开驱动失败GeoJSON,请检查");
}
try
{
dv.CopyDataSource(ds, jsonFile, new string[] { });
dv.Dispose();
GC.Collect();
}
catch (Exception ex)
{
throw new Exception("转换失败" + Environment.NewLine + ex.Message);
}
}
ds.Dispose();
ds = null;
dr.Dispose();
dr = null;
GC.Collect(); return System.IO.File.ReadAllText(jsonFile);
} private void ExtractZipFileToFolder(string filepath, string toFolder)
{
using (ZipInputStream sm = new ZipInputStream(File.OpenRead(filepath)))
{
ZipEntry entry;
while ((entry = sm.GetNextEntry()) != null)
{
//Console.WriteLine(entry.Name); string directoryName = Path.GetDirectoryName(entry.Name);
string fileName = Path.GetFileName(entry.Name); if (!Directory.Exists(toFolder))
Directory.CreateDirectory(toFolder); if (!String.IsNullOrEmpty(fileName))
{
using (FileStream streamWriter = File.Create(Path.Combine(toFolder, entry.Name)))
{
int size = ;
byte[] data = new byte[];
while (true)
{
size = sm.Read(data, , data.Length);
if (size > )
streamWriter.Write(data, , size);
else
break;
}
}
}
}
}
} //public async Task<HttpResponseMessage> PostData()
//{
// // 检查是否是 multipart/form-data
// if (!Request.Content.IsMimeMultipartContent("form-data"))
// throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); // string root = HttpContext.Current.Server.MapPath("/UploadFiles/");
// if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadFiles/")))
// {
// Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadFiles/"));
// } // HttpResponseMessage response = null;
// try
// {
// // 设置上传目录
// var provider = new MultipartFormDataStreamProvider(root);
// // 接收数据,并保存文件
// var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);
// response = Request.CreateResponse(HttpStatusCode.Accepted);
// }
// catch
// {
// throw new HttpResponseException(HttpStatusCode.BadRequest);
// }
// return response;
//} /// <summary>
/// 将zip文件解压缩到指定文件夹下
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="path">文件夹路径</param>
//private void ExtractZipFileToFolder(string zipFilePath, string path)
//{
// if (!File.Exists(zipFilePath)) return;
// if (Directory.Exists(Path.Combine(path, Path.GetFileNameWithoutExtension(zipFilePath)))) return;
// try
// {
// using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
// {
// archive.ExtractToDirectory(path);
// }
// }
// catch (Exception ex)
// {
// throw new Exception("解析压缩文件包出现异常" + Environment.NewLine + ex.Message);
// }
//} }
}
因为.net framework 4.0 不可以使用ZipArchive 解压缩zip文件。
上传html
<div style="clear:both; margin:10px; min-height:100px;max-height:350px;overflow-y:scroll;" id="addshapefile-gallery_Gallery">
<div class="galleryBackground">
<div style="opacity: 1;"> <form enctype="multipart/form-data" method="post" id="uploadForm">
<div class="field">
<label class="file-upload">
<span><strong>选择本地文件:</strong></span>
<input type="file" name="file" id="inFile" />
</label>
</div>
</form>
<span class="file-upload-status" style="opacity:1;" id="upload-status"></span>
<div style="margin-top:30px;">说明:Shapefile文件需要以Zip格式压缩 </div> </div>
</div>
</div>
webapi_uploadfile_gdal_to_geojson_and_unzipfile的更多相关文章
随机推荐
- [Android] JNI中的Local Reference
参考文章:<在 JNI 编程中避免内存泄漏> 一.Local Reference 深层解析 JNI Local Reference 的生命期是在 native method 的执行期(从 ...
- 黄聪:PHP如何实现延迟一定时间后自动刷新当前页面、自动跳转header("refresh:1;url={$url}");
//1秒后自动跳转 header("refresh:1;url={$url}"); exit; //1秒后自动刷新当前页面header("refresh:1;" ...
- SpringSecurity-ChannelProcessingFilter的作用
ChannelProcessingFilter决定的是web请求的通道,即http或https. 在springsecurity配置文件中添加这样一行 <intercept-url patter ...
- locked (a oracle.jdbc.driver.T4CConnection
发现写Oracle的线程挂住了,场景是从mysql读数据,然后写到Oracle. 1 定位线程 因为在同一台机器上运行了多个java进程,要找到对应的pid,就是连接mysql的的那个进程. ...
- 廖雪峰Java5集合-1Java集合简介-1Java结合简介
1.集合 定义:集合就是一堆东西.集合里的东西,称为元素Element 数学中的集合: 有限集合: * 一个班所有的学生组成的集合 * 一个网站所有的商品组成的集合 无限集合: * 全体自然数集合 * ...
- Oracle EXP-00091解决方法
非交互式 windows: D:\>exp scott/tiger file=employee.dmp tables=(emp,dept) linux需要加双引号 EXP-00091: [ora ...
- [UE4]Canvas Panel应用小技巧
当设置为满屏拉伸的时候,只要把“偏移左侧”和“偏移底部”都设置为0,就会自动拉伸为整屏了.再也不需要手动担心拉不满屏了.
- vue vue-resource 请求数据
main.js import Vue from 'vue'; import App from './App.vue'; /*使用vue-resource请求数据的步骤 1.需要安装vue-resour ...
- vs2015 编译google v8
转自:http://blog.csdn.net/runningman2012/article/details/54692010 系统Win10 64位,vs2015 1. git 下载depot_to ...
- MongoDb进阶实践之一 如何在Linux系统上安装和配置MongoDB
转载来源:https://www.cnblogs.com/PatrickLiu/p/8630151.html 一.NoSQL数据简介 1.NoSQL概念 NoSQL(NoSQL = Not Only ...