1. using ICSharpCode.SharpZipLib.Zip;
  2. using OSGeo.GDAL;
  3. using OSGeo.OGR;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.IO.Compression;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Web;
  14. using System.Web.Http;
  15. using System.Web.Mvc;
  16.  
  17. namespace gdal_to_geojson_service.Controllers
  18. {
  19. public class GeojsonController : ApiController
  20. {
  21.  
  22. public string Post()
  23. {
  24. // 检查是否是 multipart/form-data
  25. if (!Request.Content.IsMimeMultipartContent("form-data"))
  26. throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  27.  
  28. string root = HttpContext.Current.Server.MapPath("/UploadFiles/");
  29. if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadFiles/")))
  30. {
  31. Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadFiles/"));
  32. }
  33. try
  34. {
  35. HttpPostedFile file = HttpContext.Current.Request.Files[];
  36. string tempfilename = Guid.NewGuid().ToString();
  37. string path = Path.Combine(root, tempfilename + ".zip");
  38. file.SaveAs(path);
  39. ExtractZipFileToFolder(path, Path.Combine(root, tempfilename));
  40. string[] files = Directory.GetFiles(Path.Combine(root, tempfilename), "*.shp");
  41. if (files.Length > )
  42. {
  43. return ConvertJson(files[], Path.Combine(root, tempfilename + ".json"));
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. return "Error" + Environment.NewLine + ex.Message;
  49. }
  50. return "Error";
  51. }
  52.  
  53. private string ConvertJson(string shpFilePath, string jsonFile)
  54. {
  55. if (!File.Exists(shpFilePath))
  56. { throw new FileNotFoundException(".shp文件不存在"); }
  57.  
  58. Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
  59. Gdal.SetConfigOption("SHAPE_ENCODING", "");
  60. Ogr.RegisterAll();// 注册所有的驱动
  61. OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
  62. if (dr == null)
  63. {
  64. throw new Exception("文件不能打开,请检查");
  65. }
  66. OSGeo.OGR.DataSource ds = dr.Open(shpFilePath, );
  67.  
  68. using (OSGeo.OGR.Driver dv = OSGeo.OGR.Ogr.GetDriverByName("GeoJSON"))
  69. {
  70. if (dv == null)
  71. {
  72. throw new Exception("打开驱动失败GeoJSON,请检查");
  73. }
  74. try
  75. {
  76. dv.CopyDataSource(ds, jsonFile, new string[] { });
  77. dv.Dispose();
  78. GC.Collect();
  79. }
  80. catch (Exception ex)
  81. {
  82. throw new Exception("转换失败" + Environment.NewLine + ex.Message);
  83. }
  84. }
  85. ds.Dispose();
  86. ds = null;
  87. dr.Dispose();
  88. dr = null;
  89. GC.Collect();
  90.  
  91. return System.IO.File.ReadAllText(jsonFile);
  92. }
  93.  
  94. private void ExtractZipFileToFolder(string filepath, string toFolder)
  95. {
  96. using (ZipInputStream sm = new ZipInputStream(File.OpenRead(filepath)))
  97. {
  98. ZipEntry entry;
  99. while ((entry = sm.GetNextEntry()) != null)
  100. {
  101. //Console.WriteLine(entry.Name);
  102.  
  103. string directoryName = Path.GetDirectoryName(entry.Name);
  104. string fileName = Path.GetFileName(entry.Name);
  105.  
  106. if (!Directory.Exists(toFolder))
  107. Directory.CreateDirectory(toFolder);
  108.  
  109. if (!String.IsNullOrEmpty(fileName))
  110. {
  111. using (FileStream streamWriter = File.Create(Path.Combine(toFolder, entry.Name)))
  112. {
  113. int size = ;
  114. byte[] data = new byte[];
  115. while (true)
  116. {
  117. size = sm.Read(data, , data.Length);
  118. if (size > )
  119. streamWriter.Write(data, , size);
  120. else
  121. break;
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128.  
  129. //public async Task<HttpResponseMessage> PostData()
  130. //{
  131. // // 检查是否是 multipart/form-data
  132. // if (!Request.Content.IsMimeMultipartContent("form-data"))
  133. // throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  134.  
  135. // string root = HttpContext.Current.Server.MapPath("/UploadFiles/");
  136. // if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadFiles/")))
  137. // {
  138. // Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadFiles/"));
  139. // }
  140.  
  141. // HttpResponseMessage response = null;
  142. // try
  143. // {
  144. // // 设置上传目录
  145. // var provider = new MultipartFormDataStreamProvider(root);
  146. // // 接收数据,并保存文件
  147. // var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);
  148. // response = Request.CreateResponse(HttpStatusCode.Accepted);
  149. // }
  150. // catch
  151. // {
  152. // throw new HttpResponseException(HttpStatusCode.BadRequest);
  153. // }
  154. // return response;
  155. //}
  156.  
  157. /// <summary>
  158. /// 将zip文件解压缩到指定文件夹下
  159. /// </summary>
  160. /// <param name="zipFilePath"></param>
  161. /// <param name="path">文件夹路径</param>
  162. //private void ExtractZipFileToFolder(string zipFilePath, string path)
  163. //{
  164. // if (!File.Exists(zipFilePath)) return;
  165. // if (Directory.Exists(Path.Combine(path, Path.GetFileNameWithoutExtension(zipFilePath)))) return;
  166. // try
  167. // {
  168. // using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
  169. // {
  170. // archive.ExtractToDirectory(path);
  171. // }
  172. // }
  173. // catch (Exception ex)
  174. // {
  175. // throw new Exception("解析压缩文件包出现异常" + Environment.NewLine + ex.Message);
  176. // }
  177. //}
  178.  
  179. }
  180. }

因为.net framework 4.0 不可以使用ZipArchive 解压缩zip文件。

上传html

  1. <div style="clear:both; margin:10px; min-height:100px;max-height:350px;overflow-y:scroll;" id="addshapefile-gallery_Gallery">
  2. <div class="galleryBackground">
  3. <div style="opacity: 1;">
  4.  
  5. <form enctype="multipart/form-data" method="post" id="uploadForm">
  6. <div class="field">
  7. <label class="file-upload">
  8. <span><strong>选择本地文件:</strong></span>
  9. <input type="file" name="file" id="inFile" />
  10. </label>
  11. </div>
  12. </form>
  13. <span class="file-upload-status" style="opacity:1;" id="upload-status"></span>
  14. <div style="margin-top:30px;">说明:Shapefile文件需要以Zip格式压缩&nbsp;</div>
  15.  
  16. </div>
  17. </div>
  18. </div>

webapi_uploadfile_gdal_to_geojson_and_unzipfile的更多相关文章

随机推荐

  1. C/C++基础----特殊工具和技术 (重载new和delete,RTT,限定作用域的枚举类型,类成员指针,嵌套类,局部类,volatile,链接指示 extern “C”)

    重载new和delete 1调用operator new( 或new[])标准库函数分配足够大的.原始的.未命名的内存空间以便存储特定类型的对象 2编译器运行相应地构造函数以构造这些对象,并为其传入初 ...

  2. Eclipse安装Markdown插件

    Markdown Editor 安装Markdown插件可以实现 .md 和 .txt 文件的 Markdown 语法高亮,并提供 HTML 预览. 因为之前没有安装过别的插件,eclipse上安装插 ...

  3. Ubuntu 14.10 下Hadoop FTP文件上传配置

    最近老板提出一个需求,要用Hadoop机群管理生物数据,并且生物数据很多动辄几十G,几百G,所以需要将这些数据传到HDFS中,在此之前搭建了HUE用来图形化截面管理HDFS数据,但是有个问题,上面使用 ...

  4. 了解轮询、长轮询、长连接、websocket

    业务开发中我们往往会有一些需要即时通信的场景,比如微信扫码登录.聊天功能. 下面这四种方式都可以实现即时通信. 轮询: 浏览器通过定时器每隔一段时间向服务器端发送请求,服务器端收到请求并响应请求.没有 ...

  5. MyBatis 值的传递

    1.值的传递 - Map传值 可以通过对象获取Map传递值,在配置文件中通过 #{} 或 ${} 进行应用 查询30-40岁的用户 <!-- 值的传递 - Map传值 --> <se ...

  6. Springboot配置使用ssl,使用https

    SSL(Secure Sockets Layer 安全套接层)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密,SSL协议位于TCP/IP协议与各种应用层协议之间, ...

  7. Heap堆分析(堆转储、堆分析)

    一.堆直方图 减少内存使用时一个重要目标,在堆分析上最简单的方法是利用堆直方图.通过堆直方图我们可以快速看到应用内的对象数目,同时不需要进行完整的堆转储(因为堆转储需要一段时间来分析,而且会消耗大量磁 ...

  8. 从知名外企到创业公司做CTO是一种怎样的体验?

    这是我近期接受51CTO记者李玲玲采访的一篇文章,分享给大家. 作者:李玲玲来源:51cto.com|2016-12-30 15:47 http://cio.51cto.com/art/201612/ ...

  9. mikrotik ros CVE-2019–3924 DUDE AGENT VULNERABILITY

    原文: https://blog.mikrotik.com/security/cve-20193924-dude-agent-vulnerability.html The issue is fixed ...

  10. javascript-关于赋值的那点事

    var ary1=[3,4]; var ary2=ary1; ary2[0]=1; ary2=[6,5] console.log(ary1) console.log(ary2) 个人测试出的结果是:更 ...