fix: #188 で指定したエンドポイントでファイルを取得できない問題を修正

This commit is contained in:
usbharu 2023-12-06 21:37:00 +09:00
parent e75abfa018
commit 4fd5c487c6
2 changed files with 41 additions and 0 deletions

View File

@ -186,6 +186,7 @@ class SecurityConfig {
authorize(POST, "/api/v1/accounts", permitAll)
authorize("/auth/sign_up", hasRole("ANONYMOUS"))
authorize(GET, "/files", permitAll)
authorize(GET, "/api/v1/accounts/verify_credentials", hasAnyScope("read", "read:accounts"))

View File

@ -0,0 +1,40 @@
package dev.usbharu.hideout.core.interfaces.api.media
import dev.usbharu.hideout.application.config.LocalStorageConfig
import dev.usbharu.hideout.core.service.media.FileTypeDeterminationService
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
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)
class LocalFileController(
localStorageConfig: LocalStorageConfig,
private val fileTypeDeterminationService: FileTypeDeterminationService
) {
private val savePath = Path.of(localStorageConfig.path).toAbsolutePath()
@GetMapping("/files/{id}")
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)
}
}