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)
    }
2
  • 1
    Does this answer your question? Retrieve image from blob via Hibernate (not JDBC) Commented Apr 21, 2021 at 15:27
  • Yes, thank you I figured it out. I am not sure if this is the best way but it works. Commented Apr 21, 2021 at 16:28

1 Answer 1

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"),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.