io.javalin.http.util.MultipartUtil.kt Maven / Gradle / Ivy
The newest version!
/*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.http.util
import io.javalin.http.UploadedFile
import java.nio.charset.Charset
import javax.servlet.MultipartConfigElement
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.Part
object MultipartUtil {
private const val MULTIPART_CONFIG_ATTRIBUTE = "org.eclipse.jetty.multipartConfig"
var preUploadFunction: (HttpServletRequest) -> Unit = { req ->
val existingConfig = req.getAttribute(MULTIPART_CONFIG_ATTRIBUTE)
if (existingConfig == null) {
req.setAttribute(MULTIPART_CONFIG_ATTRIBUTE,
MultipartConfigElement(System.getProperty("java.io.tmpdir"), -1, -1, 1))
}
}
fun getUploadedFiles(req: HttpServletRequest, partName: String): List {
preUploadFunction(req)
return req.parts.filter { isFile(it) && it.name == partName }.map(this::toUploadedFile)
}
fun getUploadedFiles(req: HttpServletRequest): List {
preUploadFunction(req)
return req.parts.filter(this::isFile).map(this::toUploadedFile)
}
fun getFieldMap(req: HttpServletRequest): Map> {
preUploadFunction(req)
return req.parts.associate { part -> part.name to getPartValue(req, part.name) }
}
private fun getPartValue(req: HttpServletRequest, partName: String): List {
return req.parts.filter { isField(it) && it.name == partName }.map { filePart ->
filePart.inputStream.readBytes().toString(Charset.forName("UTF-8"))
}.toList()
}
private fun toUploadedFile(filePart: Part): UploadedFile {
return UploadedFile(
content = filePart.inputStream,
contentType = filePart.contentType,
filename = filePart.submittedFileName,
extension = filePart.submittedFileName.replaceBeforeLast(".", ""),
size = filePart.size
)
}
private fun isField(filePart: Part) = filePart.submittedFileName == null // this is what Apache FileUpload does ...
private fun isFile(filePart: Part) = !isField(filePart)
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy