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的更多相关文章
随机推荐
- locaton.href传参数
location.href = location.href.substring(0,location.href.lastIndexOf('?'))+'?typeId=' + fid + '&p ...
- sql培训
1.select--查询语句 select * from table; select cols from table; select cols from table where condition; ...
- elasticsearch 口水篇(2)CRUD Sense
Sense 为了方便.直观的使用es的REST Api,我们可以使用sense.Sense是Chrome浏览器的一个插件,使用简单. 如图: Sense安装: https://chrome.googl ...
- autoconf配置的项目,编译debug版本
./configure CFLAGS=" -g " 当然,c++代码就把 CFALGS 改成 CPPFLAGS
- C++之单例类模板
单例类模板:一个类只能有一个对象,比如超市收银系统中清点物品的仪器只有一个 设计思路: 1.构造函数,拷贝构造函数必须设计为private,防止自己生成新的对象 2.且类的指针要设计为static类型 ...
- 理解 neutron(15):Neutron Linux Bridge + VLAN/VXLAN 虚拟网络
学习 Neutron 系列文章: (1)Neutron 所实现的虚拟化网络 (2)Neutron OpenvSwitch + VLAN 虚拟网络 (3)Neutron OpenvSwitch + GR ...
- 廖雪峰Java2面向对象编程-4抽象类和接口-1抽象类
每个子类都可以覆写父类的方法 如果父类的方法没有实际意义,能否去掉方法的执行语句?子类会报编译错误 如果去掉父类的方法,就失去了多态的特性 可以把父类的方法声明为抽象方法. 如果一个class定义了方 ...
- @postconstruct初始化的操作(转载)
原文地址:https://www.cnblogs.com/qingruihappy/p/7861623.html 从Java EE 5规范开始,Servlet中增加了两个影响Servlet生命周期的注 ...
- Android多线程下载
所用知识点: 1.设置http协议字段Range “bytes=“start+”-”+end conn.addRequestProperty("Range", "byte ...
- Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK. Looked here: C:\Users\Administrator\AppData\Local\Android\sdk\tools\templates\gradle\wrapper
在Windows7上运行 “cordova build Android” 报错,如下: C:\test\hello> cordova build androidANDROID_HOME=C:\U ...