52 lines
1.6 KiB
Kotlin
52 lines
1.6 KiB
Kotlin
package com.android.trisolarisserver.component
|
|
|
|
import org.springframework.beans.factory.annotation.Value
|
|
import org.springframework.stereotype.Component
|
|
import org.springframework.web.multipart.MultipartFile
|
|
import java.nio.file.Files
|
|
import java.nio.file.Path
|
|
import java.nio.file.Paths
|
|
import java.util.UUID
|
|
|
|
@Component
|
|
class DocumentStorage(
|
|
@Value("\${storage.documents.root:/home/androidlover5842/docs}")
|
|
private val rootPath: String
|
|
) {
|
|
fun store(
|
|
propertyId: UUID,
|
|
guestId: UUID,
|
|
bookingId: UUID,
|
|
file: MultipartFile
|
|
): StoredDocument {
|
|
val safeExt = file.originalFilename?.substringAfterLast('.', "")?.takeIf { it.isNotBlank() }
|
|
val fileName = buildString {
|
|
append(UUID.randomUUID().toString())
|
|
if (safeExt != null) {
|
|
append('.')
|
|
append(safeExt.replace(Regex("[^A-Za-z0-9]"), ""))
|
|
}
|
|
}
|
|
|
|
val dir = Paths.get(rootPath, propertyId.toString(), guestId.toString(), bookingId.toString())
|
|
Files.createDirectories(dir)
|
|
val path = dir.resolve(fileName).normalize()
|
|
file.inputStream.use { input ->
|
|
Files.copy(input, path)
|
|
}
|
|
return StoredDocument(
|
|
storagePath = path.toString(),
|
|
originalFilename = file.originalFilename ?: fileName,
|
|
contentType = file.contentType,
|
|
sizeBytes = file.size
|
|
)
|
|
}
|
|
}
|
|
|
|
data class StoredDocument(
|
|
val storagePath: String,
|
|
val originalFilename: String,
|
|
val contentType: String?,
|
|
val sizeBytes: Long
|
|
)
|