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的更多相关文章
随机推荐
- WebGL和ThreeJs学习5--ThreeJS基本功能控件
Threejs 2017年6月6日 15:06 Stats: new Stats();性能监视器,性能测试的方法,引入 Stats.js http://www.hewebgl.com ...
- 黄聪:C# webBrowser控件禁用alert,confirm之类的弹窗解决方案
同样的代码,我尝试了很多次都没有成功.最后终于成功了,是因为我没有在正确的事件里面调用这段代码. private void InjectAlertBlocker() { HtmlElement hea ...
- Django--bug--__init__() got an unexpected keyword argument 'qnique'
建立模型之后,执行迁移,报如下错误: __init__() got an unexpected keyword argument 'qnique' 错误原因:模型的属性的约束添加错误,这种错误一般就是 ...
- synchronized基础
synchronized 例子 例1,没有同步的时候运行同一个对象的同一个方法的结果: public class TestSyn { public void showMsg() { try { for ...
- HAAR小波
HAAR小波分解信号或图像的“平滑”部分和“变化”部分(也许所有小波都这样?). 比如信号[1 2 3 4 5 6 7 8] 分解后(不考虑系数): [1.5 3.5 5.5 7.5] ...
- [Chrome]点击页面元素后全屏
function isFullScreen() { return (document.fullScreenElement && document.fullScreenElement ! ...
- Python twilio发短信实践
twilio注册地址 注册的时候可能会报错 最好是*** -->注册-->注册完毕后代码运行是不需要***的 https://www.twilio.com/console 需要pi ...
- MySQL学习----索引的使用
一.什么是索引?为什么要建立索引? 索引用于快速找出在某个列中有一特定值的行,不使用索引,MySQL必须从第一条记录开始读完整个表,直到找出相关的行,表越大,查询数据所花费的时间就越多,如果表中查询的 ...
- 00002 - echo命令详解
用于字符串的输出 格式 echo string 使用echo实现更复杂的输出格式控制 1.显示普通字符串: echo "It is a test" 这里的双引号完全可以省略,以下命 ...
- linux system()函数详解
system(3) - Linux man page Name system - execute a shell command Synopsis #include <stdlib.h> ...