大赵传奇

GIS解决方案,webgis , 桌面、数据、服务--QQ276605216

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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[0];
                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 > 0)
                {
                    return ConvertJson(files[0], 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, 0);

            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 = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = sm.Read(data, 0, data.Length);
                                if (size > 0)
                                    streamWriter.Write(data, 0, 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);
        //    }
        //}


    }
}
View Code

因为.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>
View Code

 

posted on 2017-02-15 16:53  赵长青  阅读(250)  评论(0)    收藏  举报