shape文件上传与展示

概述

本文讲述如何在OL中结合GeoTools实现shp数据的上传与展示。

流程

shape文件上传与展示_第1张图片
shp上传展示流程图

实现效果

shape文件上传与展示_第2张图片

shape文件上传与展示_第3张图片
线

shape文件上传与展示_第4张图片

使用技术

  1. jquery插件uploadify和ServletFileUpload实现shp文件的上传;
  2. ZipFile实现zip文件的解压;
  3. Geotools实现shp文件转换为geojson;
  4. openlayers4实现数据的展示。

实现代码

1、前端代码



    
    shp文件
    
    
    


2、后端代码

package com.lzugis.web.servlet;

import com.lzugis.helper.CommonMethod;
import com.lzugis.services.utils.ShpFormatUtil;
import com.lzugis.services.utils.ZipUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/9/10.
 */
@WebServlet(description = "shp file upload", urlPatterns =  {"/shp-upload"})
public class FileUploadServlet extends HttpServlet {

    private String rootPath = "";
    private ZipUtil zipUtil;
    private ShpFormatUtil shpUtil;
    private CommonMethod cm;

    public FileUploadServlet() {
        super();
        rootPath = "D:\\shppath\\";
        zipUtil = new ZipUtil();
        shpUtil = new ShpFormatUtil();
        cm = new CommonMethod();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //2、创建一个文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //限制单个文件大小为1M
        upload.setFileSizeMax(1024*1024);
        //限制整个表单大小为1G
        upload.setSizeMax(1024*1024*1024);
        //解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
        factory.setSizeThreshold(1024 * 500);//设置内存的临界值为500K
        File linshi = new File(rootPath);//当超过500K的时候,存到一个临时文件夹中
        factory.setRepository(linshi);
        upload.setSizeMax(1024 * 1024 * 10);//设置上传的文件总的大小不能超过5M
        Map result = new HashMap<>();
        try {
            // 1. 得到 FileItem 的集合 items
            List /* FileItem */items = upload.parseRequest(request);
            // 2. 遍历 items:
            for (FileItem item : items) {
                // 若是一个一般的表单域, 打印信息
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("utf-8");
                    System.out.println(name + ": " + value);
                }
                // 若是文件域则把文件保存到 e:\\files 目录下.
                else {
                    String fileName = item.getName();
                    long sizeInBytes = item.getSize();
//                    System.out.println(fileName);
//                    System.out.println(sizeInBytes);
                    InputStream in = item.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    //文件最终上传的位置
                    fileName = rootPath + fileName;
                    OutputStream out = new FileOutputStream(fileName);
                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    out.close();
                    in.close();
                    String shpPath = zipUtil.unZipFiles(fileName, rootPath);
                    System.out.println("shp path"+shpPath);
                    StringBuffer json = shpUtil.shp2Json(shpPath);
                    result.put("status", "200");
                    result.put("geojson", json.toString());
//                    cm.append2File(rootPath + "json.json", json.toString());
                    JSONObject.writeJSONString(result, response.getWriter());
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}
···
3、zip解压类
```java
package com.lzugis.services.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipUtil {
    /**
     * 解压文件到指定目录
     * 解压后的文件名,和之前一致
     * @param zipPath   待解压的zip文件路径
     * @param descDir   指定目录
     */
    @SuppressWarnings("rawtypes")
    public String unZipFiles(String zipPath, String descDir) throws IOException {
        String shpPath = "";
        File zipFile = new File(zipPath);
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码
        String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.'));
        File pathFile = new File(descDir+name);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + name +"/"+ zipEntryName).replaceAll("\\*", "/");
            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 输出文件路径信息
            FileOutputStream out = new FileOutputStream(outPath);
            if(outPath.substring(outPath.length()-3,outPath.length()).equals("shp")){
                shpPath = outPath;
            }
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        return shpPath;
    }
}

4、shp文件转换

package com.lzugis.services.utils;

import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONObject;
import com.vividsolutions.jts.geom.Geometry;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
import org.opengis.feature.simple.SimpleFeature;

import java.io.File;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class ShpFormatUtil {

    public StringBuffer shp2Json(String shpPath){
        StringBuffer sb = new StringBuffer();
        FeatureJSON fjson = new FeatureJSON();
        try{
            sb.append("{\"type\": \"FeatureCollection\",\"features\": ");

            File file = new File(shpPath);
            ShapefileDataStore shpDataStore = null;

            shpDataStore = new ShapefileDataStore(file.toURL());
            //设置编码
            Charset charset = Charset.forName("GBK");
            shpDataStore.setCharset(charset);
            String typeName = shpDataStore.getTypeNames()[0];
            SimpleFeatureSource featureSource = null;
            featureSource =  shpDataStore.getFeatureSource (typeName);
            SimpleFeatureCollection result = featureSource.getFeatures();
            SimpleFeatureIterator itertor = result.features();
            JSONArray array = new JSONArray();
            while (itertor.hasNext())
            {
                SimpleFeature feature = itertor.next();
                Geometry geo = (Geometry) feature.getAttribute("the_geom");

                StringWriter writer = new StringWriter();
                fjson.writeFeature(feature, writer);
                JSONObject json = new JSONObject(writer.toString());
                array.put(json);
            }
            itertor.close();
            sb.append(array.toString());
            sb.append("}");
        }
        catch(Exception e){
            e.printStackTrace();

        }
        return sb;
    }
}

技术博客
CSDN:http://blog.csdn.NET/gisshixisheng
博客园:http://www.cnblogs.com/lzugis/
在线教程
http://edu.csdn.Net/course/detail/799
Github
https://github.com/lzugis/
联系方式

类型 内容
qq 1004740957
公众号 lzugis15
e-mail [email protected]
webgis群 452117357
Android群 337469080
GIS数据可视化群 458292378
LZUGIS

你可能感兴趣的:(shape文件上传与展示)