此函数用于处理上传的ZIP文件并将其转换为GeoJSON格式的字符串。具体步骤如下:
- 验证上传文件是否为ZIP格式。
- 创建临时目录以解压ZIP文件。
- 解压缩ZIP文件至临时目录。
- 查找解压后的.shp文件。
- 如果缺少.shx或.dbf辅助文件,则创建空文件。
- 读取Shapefile数据。
- 将特征集合转换为GeoJSON格式。
- 清理临时文件和资源。
函数返回转换后的GeoJSON字符串。
public String shpImport(MultipartFile zipFile) throws IOException {
// Check if the uploaded file has the .zip extension
if (!zipFile.getOriginalFilename().toLowerCase().endsWith(".zip")) {
throw new IllegalArgumentException("Only .zip files are allowed.");
}
// Create a temporary directory to extract the ZIP file
File tempDir = File.createTempFile("shp_upload_", "");
if (tempDir.exists()) {
tempDir.delete();
}
tempDir.mkdir();
// Unzip the file to the temporary directory
try (ZipFile zip = new ZipFile(convertMultipartFileToFile(zipFile))) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File entryDestination = new File(tempDir, entry.getName());
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
entryDestination.getParentFile().mkdirs();
try (FileOutputStream out = new FileOutputStream(entryDestination)) {
FileUtils.copyInputStreamToFile(zip.getInputStream(entry), entryDestination);
}
}
}
}
// Find the .shp file in the extracted files
File[] shpFiles = tempDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".shp"));
if (shpFiles == null || shpFiles.length == 0) {
throw new IllegalArgumentException("The ZIP file does not contain a .shp file.");
}
File shpFile = shpFiles[0];
File shxFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".shx");
File dbfFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".dbf");
// Handle the missing .shx and .dbf files gracefully by creating empty files
if (!shxFile.exists()) {
shxFile.createNewFile();
}
if (!dbfFile.exists()) {
dbfFile.createNewFile();
}
// Read the shapefile
FileDataStore store = FileDataStoreFinder.getDataStore(shpFile);
SimpleFeatureCollection featureCollection = store.getFeatureSource().getFeatures();
// Convert features to GeoJSON
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
FeatureJSON featureJSON = new FeatureJSON();
try (FeatureIterator<?> features = featureCollection.features()) {
featureJSON.writeFeatureCollection(featureCollection, outputStream);
return outputStream.toString();
} finally {
// Clean up temporary files
store.dispose();
FileUtils.deleteDirectory(tempDir);
}
}
函数返回转换后的WKT字符串。
public String shpImport(MultipartFile zipFile) throws IOException {
// Check if the uploaded file has the .zip extension
if (!zipFile.getOriginalFilename().toLowerCase().endsWith(".zip")) {
throw new IllegalArgumentException("Only .zip files are allowed.");
}
// Create a temporary directory to extract the ZIP file
File tempDir = File.createTempFile("shp_upload_", "");
if (tempDir.exists()) {
tempDir.delete();
}
tempDir.mkdir();
// Unzip the file to the temporary directory
try (ZipFile zip = new ZipFile(convertMultipartFileToFile(zipFile))) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File entryDestination = new File(tempDir, entry.getName());
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
entryDestination.getParentFile().mkdirs();
try (FileOutputStream out = new FileOutputStream(entryDestination)) {
FileUtils.copyInputStreamToFile(zip.getInputStream(entry), entryDestination);
}
}
}
}
// Find the .shp file in the extracted files
File[] shpFiles = tempDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".shp"));
if (shpFiles == null || shpFiles.length == 0) {
throw new IllegalArgumentException("The ZIP file does not contain a .shp file.");
}
File shpFile = shpFiles[0];
File shxFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".shx");
File dbfFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".dbf");
// Handle the missing .shx and .dbf files gracefully by creating empty files
if (!shxFile.exists()) {
shxFile.createNewFile();
}
if (!dbfFile.exists()) {
dbfFile.createNewFile();
}
// Read the shapefile
FileDataStore store = FileDataStoreFinder.getDataStore(shpFile);
SimpleFeatureCollection featureCollection = store.getFeatureSource().getFeatures();
// Convert features to WKT
WKTWriter wktWriter = new WKTWriter();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (SimpleFeatureIterator features = featureCollection.features()) {
while (features.hasNext()) {
SimpleFeature feature = features.next();
String wkt = wktWriter.write((Geometry) feature.getDefaultGeometry());
outputStream.write((wkt + "\n").getBytes());
}
return outputStream.toString();
} finally {
// Clean up temporary files
store.dispose();
FileUtils.deleteDirectory(tempDir);
}
}
private File convertMultipartFileToFile(MultipartFile file) throws IOException {
File convFile = File.createTempFile("temp", null);
try (FileOutputStream fos = new FileOutputStream(convFile)) {
fos.write(file.getBytes());
}
return convFile;
}
所需依赖
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>24.1</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-geojson</artifactId>
<version>24.1</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-main</artifactId>
<version>24.1</version>
</dependency>
若依赖下载失败,可在pom文件中添加
<repositories>
<repository>
<id>osgeo</id>
<name>osgeo</name>
<url>https://repo.osgeo.org/repository/release/</url>
</repository>
</repositories>