依赖
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>25.2</version>
</dependency>
/upload上传接口
import org.geotools.data.Query;
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.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
@PostMapping("/upload")
public UploadReq upload(MultipartFile file){
UploadReq response = new UploadReq();
String packFileStr = 'E:/upload';
File folder = new File(packFileStr);
if (!folder.exists()) {
folder.mkdirs();
}
String fileName = file.getOriginalFilename();// shape压缩包名
String packFilePath = packFileStr + File.separator + fileName;
File files = new File(packFilePath);
try{
file.transferTo(files);
} catch(IOException e){
e.printStackTrace();
throw new RuntimeException("压缩文件到:" + packFileStr + " 失败!");
}
//zip解压---------------------------------------------------
UnPackeUtil.unPackZip(files, null, packFileStr);
// 获取解压文件目录
fileName = fileName.substring(0,fileName.lastIndexOf('.'));
String folderPath = packFileStr + File.separator + fileName;
File sfiles = new File(folderPath);
File[] filesList = sfiles.listFiles();
System.out.println("解压文件目录:" +filesList+folderPath);
// 获取解压文件shape路径
String shapePath = "";
for(int i = 0;i<filesList.length;i++){
String path = filesList[i].getPath();
String type = path.substring(path.length()-4,path.length());
// System.out.println("解压格式:"+type );
if(type.equals(".shp")){
shapePath = path;
}
}
System.out.println("解压文件shape路径:"+shapePath );
// 获取shape属性数据信息-----------------------
File shpfile = new File(shapePath);
String tableName = null;
try{
ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpfile.toURI().toURL());
//设置编码,防止中文乱码
Charset charset = Charset.forName("GBK");
shapefileDataStore.setCharset(charset);
tableName = shapefileDataStore.getTypeNames()[0];
System.out.println("typeName:"+tableName);
//根据图层名称来获取要素的source
SimpleFeatureSource featureSource = shapefileDataStore.getFeatureSource(tableName);
//读取bbox
ReferencedEnvelope bbox = featureSource.getBounds();
//读取投影
CoordinateReferenceSystem crs = featureSource.getSchema().getCoordinateReferenceSystem();
//特征总数
int count = featureSource.getCount(Query.ALL);
//获取当前数据的geometry类型(点、线、面)
GeometryType geometryType = featureSource.getSchema().getGeometryDescriptor().getType();
//读取要素
SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featureSource.getFeatures();
// shape名称,例如shopping.shp tableName为shopping
shapeName = tableName;
response.setShapeTableName(tableName);
// 字段
List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();
SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();
System.out.println("是否找到表" + addShapeTableService.findTable(tableName));
if(addShapeTableService.findTable(tableName)){// 查询是否找到表,找到删除
// 删除表--------------------
addShapeTableService.delTableSql(tableName);
}
// 新建表--------------------
int code = CoordinateType.getByWkt(crs.getName().getCode());
if(code == 0){
return null;
}
addShapeTableService.addTableSql(tableName, attributes,code);
// 表插入数据
addShapeTableService.addTableData(tableName, attributes,simpleFeatureIterator,code);
}catch (Exception e){
e.printStackTrace();
}
response.setUrl(packFileStr);
return response;
}
UnPackeUtil.java
--解压参考连接:SpringBoot(Java)实现zip、rar压缩包上传及解压_springboot上传zip并解压_一恍过去的博客-CSDN博客
package cn.o.util;
import net.lingala.zip4j.core.ZipFile;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class UnPackeUtil {
private static final Logger logger = LoggerFactory.getLogger(UnPackeUtil.class);
/**
* zip文件解压
*
* @param destPath 解压文件路径
* @param zipFile 压缩文件
* @param password 解压密码(如果有)
*/
public static void unPackZip(File zipFile, String password, String destPath) {
try {
ZipFile zip = new ZipFile(zipFile);
/*zip4j默认用GBK编码去解压,这里设置编码为GBK的*/
zip.setFileNameCharset("GBK");
logger.info("begin unpack zip file....");
zip.extractAll(destPath);
// 如果解压需要密码
if (password != null) {
if (zip.isEncrypted()) {
zip.setPassword(password);
}
}
} catch (Exception e) {
logger.error("解压失败:", e.getMessage(), e);
}
}
/**
* rar、zip、tar文件解压
*
* @param newFile file文件
* @param targetFilePath 解压保存路径
*/
public static void unPackRar(File newFile, String targetFilePath) {
RandomAccessFile randomAccessFile =null;
IInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(newFile.getPath(), "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
int[] in = new int[inArchive.getNumberOfItems()];
for (int i = 0; i < in.length; i++) {
in[i] = i;
}
inArchive.extract(in, false, new ExtractCallback(inArchive,"366",targetFilePath));
}catch (FileNotFoundException | SevenZipException e) {
e.printStackTrace();
}
}
}
CoordinateType.java
package cn.o.common.shapefile;
import cn.o.common.req.shape.CoordinateTypeReq;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
@Getter
@AllArgsConstructor
public class CoordinateType {
static int srs = 0;
public static int getByWkt(String wkt) {
List<CoordinateTypeReq> list = new ArrayList<>();
CoordinateTypeReq coordinateTypeReq = new CoordinateTypeReq("GCS_WGS_1984",4326);
list.add(coordinateTypeReq);
list.forEach((item)->{
if(item.getWkt().equals(wkt)){
srs = item.getSrs();
}
});
return srs;
}
public List<CoordinateTypeReq> getList(){
List<CoordinateTypeReq> list = new ArrayList<>();
CoordinateTypeReq coordinateTypeReq = new CoordinateTypeReq("GCS_WGS_1984",4326);
list.add(coordinateTypeReq);
return list;
}
}
addShapeTableServiceImpl
@Override
public void addTableSql(String tableName, List<AttributeDescriptor> attributes, int crs){
// shape表新建 create table if not exists tableName(the_geom geometry("geometry",4326),gml_id varchar(255),Name varchar(255),....)
StringBuilder historyTableSql = new StringBuilder();
historyTableSql.append("create table if not exists ").append(tableName).append("(");
for (int n = 0; n < attributes.size(); n++) {
String column = attributes.get(n).getLocalName();
if(column.equals("the_geom")){
// historyTableSql.append(column).append(" geometry");
// 带坐标系入库
historyTableSql.append("the_geom").append(" geometry(\"geometry\",").append(crs).append(")");
}else{
historyTableSql.append(column).append(" varchar(255)");
}
if (n < attributes.size() - 1) {
historyTableSql.append(",");
}
}
historyTableSql.append(")");
System.out.print("新建表sql语句:"+historyTableSql);
addShapeTableMapper.executeSQL(historyTableSql.toString());
System.out.println("新建成功");
}
@Override
public void addTableData(String tableName, List<AttributeDescriptor> attributes, SimpleFeatureIterator simpleFeatureIterator, int crs){
// shape数据表添加数据--insert into tableName values(st_geometryfromtext('POINT(132.22 31.24)',4326)),'无锡',...)
while(simpleFeatureIterator.hasNext()) {
StringBuilder sql = new StringBuilder();
sql.append("insert into ").append(tableName);
sql.append(" values(");
SimpleFeature simpleFeature = simpleFeatureIterator.next();
for (int n = 0; n < attributes.size(); n++) {
if(attributes.get(n).getLocalName().equals("the_geom")){
sql.append("st_geometryfromtext('");
sql.append(simpleFeature.getAttribute(attributes.get(n).getLocalName()));
sql.append("',").append(crs).append(")");
}else {
sql.append("'");
sql.append(simpleFeature.getAttribute(attributes.get(n).getLocalName()));
sql.append("'");
}
if (n < attributes.size() - 1) {
sql.append(",");
}
}
sql.append(")");
// System.out.println("数据插入语法"+sql);
addShapeTableMapper.executeSQL(sql.toString());
}
}
@Override
public void delTableSql(String tableName){
StringBuilder sql = new StringBuilder();
sql.append("drop table ").append(tableName).append(";");
sql.append("drop sequence if exists sequence_").append(tableName).append(";");
addShapeTableMapper.deleteSQL(sql.toString());
System.out.println("删除成功");
}
mapper.xml
<insert id="executeSQL">
${sql}
</insert>
<delete id="deleteSQL">
${sql}
</delete>