【发布时间】:2021-01-28 21:28:30
【问题描述】:
我正在学习 Kotlin,但在理解如何进行时遇到了一些困难
目前我有一个从前端发送的 kml 文件,但现在我想接受 geoJson 并存储这个 i 数据库 -> 所以我需要创建Kotlin 中用于验证文件类型并根据类型返回正确对象的函数。
这个函数接受 kml 文件并调用 parseKmlToPolygons
fun parseKmlToPolygons(file: MultipartFile, applicationConfiguration: ApplicationConfiguration): Geometry {
if (file.size > applicationConfiguration.getMaxKmlUploadFileSizeLimitInBytes()) {
throw FileUploadSizeLimitReachedException()
}
return parseMultiParFileToPolygons(file.inputStream)
}
private fun parseKmlToPolygons(content: InputStream): Geometry {
try {
val kml = Kml.unmarshal(content) ?: throw InvalidKmlException("Failed to parse the kml file")
return toGeometry(kml.feature)
} catch (ex: IllegalArgumentException) {
throw InvalidKmlException(ex.localizedMessage, ex)
} catch (ex: InvalidGeometryException) {
throw InvalidKmlException(ex.localizedMessage, ex)
}
}
所以我可能需要创建一个检测正确文件的函数,但是我可以在这里返回类型 Any 吗?另外,是否可以从 inputStream 中获取文件的类型?
private fun detectFileType():Any {
}
如果我在这里不是很清楚,我很抱歉,我所需要的只是替换采用 kml 文件的函数,以便能够采用 kml 或 geoJson
更新
//todo would be better to have detection logic separate
private fun parseKmlToPolygons(file: MultipartFile): Geometry {
val fileExtension: String = FilenameUtils.getExtension(file.originalFilename)
if (fileExtension == PolygonFileType.KML.name) {
return parseKmlToPolygons(file.inputStream)
} else if (fileExtension == PolygonFileType.GEOJSON.name) {
return parseKmlToPolygons(file.inputStream)
}
throw FormatNotSupportedException("File format is not supported")
}
【问题讨论】:
-
我宁愿使用枚举类 PolygonFileType { KML, GEOJSON } 作为检测文件类型()的返回类型:PolygonFileType。
-
@HonzaMusil 确实让它保持不变,因为它永远不会改变,但是,我需要检测文件类型,你知道从输入流中找到文件类型的有效方法吗?
-
docs.spring.io/spring-framework/docs/current/javadoc-api/org/… 包含 originalFileName 和 contentType