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格式压缩&nbsp;</div> </div>
</div>
</div>

webapi_uploadfile_gdal_to_geojson_and_unzipfile的更多相关文章

随机推荐

  1. 黄聪:在.NET中使用GeckoFX 29

    GeckoFX is a .NET control, that works similarly to “System.Windows.Forms.WebBrowser” Control, while ...

  2. asp.net core项目 部署在 linux上

    第一步 安装 .net core https://www.microsoft.com/net/learn/get-started/linuxubuntu 第二步 运行你的asp.net core 项目 ...

  3. C++中sort函数小结

    我们都知道,sort函数是C++标准库<algorithm>中的一个库函数.它的功能是对数组/容器中的元素进行排序.用法示例如下: 一.对数组进行排序 示例: int a[] = {1,3 ...

  4. Ubuntu 14.10 下Hadoop代码编译问题总结

    问题1  protoc (compile-protoc) on project hadoop-common: org.apache.maven.plugin.MojoExecutionExceptio ...

  5. P1706 全排列问题

    题解:(其实我认为它就是个循环) #include<iostream> #include<cstdio> #include<iomanip> using names ...

  6. python 字符转换记录

    1.unicode转utf-8格式: a="unicode格式的字符" a=a.encode("utf-8") 2.utf-8转unicode格式: s2 = ...

  7. pj1--学生信息管理系统

    1.根据班上的情况做一个班级学生信息管理系统.包含功能有每日签到.学分管理.个人信息管理 2.要求:用winform+序列化(本地化)的技术实现,以教师机做服务器,要有文件保存.读取.还要有上传头像功 ...

  8. Oracle 表空间的概念

    表空间   在数据库系统中,存储空间是较为重要的资源,合理利用空间,不但能节省空间,还可以提高系统的效率和工作性能. Oracle 可以存放海量数据,所有数据都在数据文件中存储.而数据文件大小受操作系 ...

  9. awk 改名

    awk 改名 echo ""|awk 'END{for(i=2;i<=100;i++){system("mv securitycode\ \("i&quo ...

  10. python面向对象 : 继承

    一. 初识继承 继承是一种创建新类的方式,在python中,新建的类可以继承一个或多个父类,父类又可称为基类或超类,新建的类称为派生类或子类. 当我们在定义多个类的时候,发现要用到相同的方法或变量,如 ...