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. ASP防止SQL注入

    '防止SQL注入'http://0.0.0.0/bzhs/login.asp?logType=edit';WAITFOR DELAY '0:0:5' --logType = Replace(Repla ...

  2. html多个水平并列组件自适应等高的做法

    做一个div盒子,设置over-flow:hidden,设置高度为auto.然后再盒子里排列若干inline-block,inline元素. 自适应的话常用做法是用line-height,font-s ...

  3. ALGO-27_蓝桥杯_算法训练_FBI树(树,递归)

    问题描述 我们可以把由“”和“”组成的字符串分为三类:全“”串称为B串,全“”串称为I串,既含“”又含“”的串则称为F串. FBI树是一种二叉树,它的结点类型也包括F结点,B结点和I结点三种.由一个长 ...

  4. 【spring】之事物配置,声明式事务管理和基于@Transactional注解的使用

    http://blog.csdn.net/bao19901210/article/details/41724355

  5. C++进阶--处理拷贝赋值运算符中自赋值的情况

    //############################################################################ /* * 处理拷贝赋值运算符=中自赋值的情 ...

  6. Netty简单的HTTP服务器

    本文转载自:https://www.cnblogs.com/luangeng/p/7875710.html HTTP协议:略 基于Netty的HTTP协议栈可以方便的进行异步非阻塞的HTTP服务器的开 ...

  7. Global配置接口访问日志以及测试日志记录

    在客户端请求接口时,经常会出现接口相应慢,接口等待超时,接口错误,为了这事相信不少后台开发者为此背锅,记下请求日志,拿出有力证据这才是关键. 1.接口请求错误记录 很多时候接口请求出现的500,404 ...

  8. 廖雪峰Java3异常处理-1错误处理-2捕获异常

    1捕获异常 1.1 finally语句保证有无错误都会执行 try{...}catch (){...}finally{...} 使用try...catch捕获异常 可能发生异常的语句放在try{... ...

  9. [UE4]对象

    类型和类 1.类型,Type,代表了数据含义,程序员可以对数据进行哪些操作.如果是整数,就可以进行加减乘除:如果是字符串,可以进行打印.连接.但不能对字符串进行加减乘除. 2.类,class,自定义类 ...

  10. CRM 2016 升级CRM365之注意事项

    https://docs.microsoft.com/zh-cn/previous-versions/dynamicscrm-2016/deployment-administrators-guide/ ...