0

I have built an app with a Spring Boot Gradle Kotlin Backend, that can store and upload Multipart files to a Postgres database. The data is stored in a ByteArray. So far everything is working fine.

Now I want to add an Image URL to make it available in my JSON Object to later grab it and display it on my client side like the ones on Unsplash.

imageURL

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

File model

@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"
)

Store

    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)
    }
BrownieBrown
  • 115
  • 11
  • 1
    Does this answer your question? [Retrieve image from blob via Hibernate (not JDBC)](https://stackoverflow.com/questions/9049488/retrieve-image-from-blob-via-hibernate-not-jdbc) – crizzis Apr 21 '21 at 15:27
  • Yes, thank you I figured it out. I am not sure if this is the best way but it works. – BrownieBrown Apr 21 '21 at 16:28

1 Answers1

0

After reading the suggestion above I came up with this and it works. Controller Update

@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()
    }

File Model update

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