org.http4k.multipart.DiskLocation.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of http4k-multipart Show documentation
Show all versions of http4k-multipart Show documentation
Http4k multipart form support
package org.http4k.multipart
import java.io.Closeable
import java.io.File
import java.nio.file.FileSystemException
import java.nio.file.Files
import java.util.UUID
/**
* Provides the management of the on-disk persistence for mulitpart files which are too big
* to be processed in-memory.
*/
interface DiskLocation : Closeable {
fun createFile(filename: String?): MultipartFile
companion object {
fun Temp(diskDir: File = Files.createTempDirectory("http4k-mp").toFile()) =
object : DiskLocation {
override fun createFile(filename: String?): MultipartFile =
TempFile(
File.createTempFile(
filename ?: (UUID.randomUUID().toString() + "-"),
".tmp", diskDir
)
)
override fun close() {
diskDir.listFiles()?.forEach { it.delete() }
diskDir.delete()
}
}
fun Permanent(diskDir: File = Files.createTempDirectory("http4k-mp").toFile()) =
object : DiskLocation {
override fun createFile(filename: String?): MultipartFile =
PermanentFile(
File.createTempFile(
filename ?: (UUID.randomUUID().toString() + "-"),
".tmp", diskDir
)
)
override fun close() {}
}
}
}
interface MultipartFile : Closeable {
fun file(): File
override fun close()
}
internal class TempFile(private val file: File) : MultipartFile {
override fun file() = file
override fun close() {
if (file.exists() && !file.delete()) throw FileSystemException("Failed to delete file")
}
}
internal class PermanentFile(private val file: File) : MultipartFile {
override fun file() = file
override fun close() {
// do nothing
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy