【问题标题】:How to insert an Image URL for Images stored in Postgres into a Spring Boot Model如何将存储在 Postgres 中的图像的图像 URL 插入 Spring Boot 模型
【发布时间】:2021-04-21 14:28:23
【问题描述】:

我用 Spring Boot Gradle Kotlin 后端构建了一个应用程序,它可以存储 Multipart 文件并将其上传到 Postgres 数据库。数据存储在 ByteArray 中。到目前为止一切正常。

现在我想添加一个图像 URL 以使其在我的 JSON 对象中可用,以便稍后抓取它并将其显示在我的客户端,就像 Unsplash 上的那样。

图片网址

"imageURL": "https://xyz.jpg"

文件模型

@Entity
@Table(name = "file")
data class File(
    @Id
    val id: UUID = UUID.randomUUID(),
    val createdAt: LocalDateTime = LocalDateTime.now(),
    var updatedAt: LocalDateTime = LocalDateTime.now(),
    var likes: Int = 0,
    var likedByUser: Boolean = false,
    var description: String = "",
    val downloadLink: URI = URI("https://unsplasy-backend.herokuapp.com/files/download/$id"),
    var name: String = "",
    var type: String = "",

    @Basic(fetch = FetchType.LAZY)
    private val data: ByteArray = byteArrayOf(),

    val imageURL: TODO = "TODO"
)

商店

    fun store(file: MultipartFile): File {
        val fileName = file.originalFilename.toString()
        val fileToSave = File(
            name = fileName,
            type = file.contentType.toString(),
            data = file.bytes
        )

        return fileRepository.save(fileToSave)
    }

【问题讨论】:

标签: arrays spring postgresql kotlin


【解决方案1】:

在阅读了上面的建议后,我想出了这个并且它有效。 控制器更新

@GetMapping("/files/image/{id}")
    fun displayImage(@PathVariable id: UUID, response: HttpServletResponse) {
        val file = fileService.getFile(id)
        val data = fileService.getData(file)
        response.contentType = file.type
        response.outputStream.write(data)
        response.outputStream.close()
    }

文件模型更新

val imageURL: URL = URL("https://unsplasy-backend.herokuapp.com/files/image/$id"),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2022-09-27
    • 2011-07-25
    • 2019-07-24
    • 2013-09-21
    • 2014-10-01
    • 2018-07-22
    相关资源
    最近更新 更多