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的更多相关文章
随机推荐
- C/C++基础----特殊工具和技术 (重载new和delete,RTT,限定作用域的枚举类型,类成员指针,嵌套类,局部类,volatile,链接指示 extern “C”)
重载new和delete 1调用operator new( 或new[])标准库函数分配足够大的.原始的.未命名的内存空间以便存储特定类型的对象 2编译器运行相应地构造函数以构造这些对象,并为其传入初 ...
- Eclipse安装Markdown插件
Markdown Editor 安装Markdown插件可以实现 .md 和 .txt 文件的 Markdown 语法高亮,并提供 HTML 预览. 因为之前没有安装过别的插件,eclipse上安装插 ...
- Ubuntu 14.10 下Hadoop FTP文件上传配置
最近老板提出一个需求,要用Hadoop机群管理生物数据,并且生物数据很多动辄几十G,几百G,所以需要将这些数据传到HDFS中,在此之前搭建了HUE用来图形化截面管理HDFS数据,但是有个问题,上面使用 ...
- 了解轮询、长轮询、长连接、websocket
业务开发中我们往往会有一些需要即时通信的场景,比如微信扫码登录.聊天功能. 下面这四种方式都可以实现即时通信. 轮询: 浏览器通过定时器每隔一段时间向服务器端发送请求,服务器端收到请求并响应请求.没有 ...
- MyBatis 值的传递
1.值的传递 - Map传值 可以通过对象获取Map传递值,在配置文件中通过 #{} 或 ${} 进行应用 查询30-40岁的用户 <!-- 值的传递 - Map传值 --> <se ...
- Springboot配置使用ssl,使用https
SSL(Secure Sockets Layer 安全套接层)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密,SSL协议位于TCP/IP协议与各种应用层协议之间, ...
- Heap堆分析(堆转储、堆分析)
一.堆直方图 减少内存使用时一个重要目标,在堆分析上最简单的方法是利用堆直方图.通过堆直方图我们可以快速看到应用内的对象数目,同时不需要进行完整的堆转储(因为堆转储需要一段时间来分析,而且会消耗大量磁 ...
- 从知名外企到创业公司做CTO是一种怎样的体验?
这是我近期接受51CTO记者李玲玲采访的一篇文章,分享给大家. 作者:李玲玲来源:51cto.com|2016-12-30 15:47 http://cio.51cto.com/art/201612/ ...
- mikrotik ros CVE-2019–3924 DUDE AGENT VULNERABILITY
原文: https://blog.mikrotik.com/security/cve-20193924-dude-agent-vulnerability.html The issue is fixed ...
- javascript-关于赋值的那点事
var ary1=[3,4]; var ary2=ary1; ary2[0]=1; ary2=[6,5] console.log(ary1) console.log(ary2) 个人测试出的结果是:更 ...