feat: 画像読み込みに対応

This commit is contained in:
usbharu 2024-08-12 22:13:16 +09:00
parent be07a89b7f
commit 2bc9b17cdc
Signed by: usbharu
GPG Key ID: 6556747BF94EEBC8
2 changed files with 27 additions and 3 deletions

View File

@ -82,6 +82,7 @@ class SecurityConfig {
authorize(GET, "/auth/sign_up", hasRole("ANONYMOUS"))
authorize(POST, "/auth/sign_up", permitAll)
authorize(GET, "/users/{username}/posts/{postId}", permitAll)
authorize(GET, "/files/*", permitAll)
authorize(anyRequest, authenticated)
}

View File

@ -16,21 +16,44 @@
package dev.usbharu.hideout.core.interfaces.api.media
import dev.usbharu.hideout.core.config.LocalStorageConfig
import dev.usbharu.hideout.core.external.media.FileTypeDeterminer
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.PathResource
import org.springframework.core.io.Resource
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import java.nio.file.Path
import kotlin.io.path.name
@Controller
@ConditionalOnProperty("hideout.storage.type", havingValue = "local", matchIfMissing = true)
interface LocalFileController {
class LocalFileController(
localStorageConfig: LocalStorageConfig,
private val fileTypeDeterminationService: FileTypeDeterminer
) {
private val savePath = Path.of(localStorageConfig.path).toAbsolutePath()
@GetMapping("/files/{id}")
fun files(@PathVariable("id") id: String): ResponseEntity<Resource>
fun files(@PathVariable("id") id: String): ResponseEntity<Resource> {
val name = Path.of(id).name
val path = savePath.resolve(name)
val mimeType = fileTypeDeterminationService.fileType(path, name)
val pathResource = PathResource(path)
return ResponseEntity
.ok()
.contentType(MediaType(mimeType.type, mimeType.subtype))
.contentLength(pathResource.contentLength())
.body(pathResource)
}
@GetMapping("/users/{user}/icon.jpg", "/users/{user}/header.jpg")
fun icons(): ResponseEntity<Resource> {
@ -41,4 +64,4 @@ interface LocalFileController {
.contentLength(pathResource.contentLength())
.body(pathResource)
}
}
}