Home > Mobile >  Which approach is better to upload image to entity in spring boot rest api application?
Which approach is better to upload image to entity in spring boot rest api application?

Time:11-17

For example I have enitity Event with fields name, description etc. And then I want to add new field String "photo" that will be reference to a photo. So it is easy to add new field to entity, Hibernate will update the table of entity Event.

Also I have POSTmethod saveEvent(Event event) in EventRestController class to save new Entity. Suppose, that I responsible only for backend, and I only need give endpoints to the frontend developers. My method createEvent() returns ReponseEntity. Suppose I changing my method to:

public ResponseEntity<Event> createEvent(@RequestBody Event event,
            @RequestParam("image") MultipartFile multipartFile) throws IOException {
    ...
    event.setPhoto(StringUtils.cleanPath(multipartFile.getOriginalFilename()));
    // save event in repo
    // upload image to directory event-photos/{eventId}
    // return event with photo field
}

And then my GET method will be return ReponseEntity with field photo:

public ResponseEntity<Event> getEventById(@PathVariable(value = "eventId") long eventId) {
    // returns Event with field "photo"
}

And here is my question. Is this enough to show image of this Event for frontend developers? Is this a good approach to link image reference to the Entity?

CodePudding user response:

I have the same problem in my application, and I think it will not work, you will not be able to send the Event in the body and the @RequestParam as a MultipartFile.

I solved this problem creating two routes, one to POST the object, and a second one to send the file which receives the object id in the path and the MultipartFile in the @RequestParam.

The same idea to download the file, I have one GET route to return the object, and a second GET route that receives the object id and return the file.

CodePudding user response:

if you can want return an image in object Event or same. You should convert to base64

or you can return only that file in body with content-type=application/octet-stream

document refer: Baeldung

  • Related