Retreive BLOB from Database with image Using Spring MVC and Thymeleaf

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Retreive BLOB from Database with image Using Spring MVC and Thymeleaf

NunoSaa
I have some problems presenting an image on frontend using spring mvc with hibernate to retrieve the image stored into a blob on database.

Entity:

    @Lob
    @Column(length = 100000)
    private byte[] foto;
   
    public byte[] getFoto() {
    return foto;
    }
   
    public void setFoto(byte[] foto) {
    this.foto = foto;
    }

Controller:

    @GetMapping("/view")
    public ModelMap viewVehicle(@RequestParam(value = "id", required = false) Vehicle vehicle, Model model) {
    if (vehicle == null) {
    vehicle = new Vehicle();
    }
   
    return new ModelMap("vehicle", vehicle);
    }

HTML:

    th:src="*{'data:image/png;base64,'+ foto}"

But the view run without error's but the image not displayed.

I experimented a lot of solutions i've found on internet, but anything worked.

Any consideration to help-me resolve this situation?

Greetings
Reply | Threaded
Open this post in threaded view
|

Re: Retreive BLOB from Database with image Using Spring MVC and Thymeleaf

Reiju
your foto is a byte array - try to convert it to string.

Or u can do something like this (this is not the best solution):
1. HTML:
th:src="*{'/img/' + entity.id}"

2. Controller
@GetMapping("/img/{id}")
public void getImage(@PathVariable("id") Long id, HttpServletResponse response) {
        imageService.writeImageToRespose(id, response);
}

3. Service
@Override
public void writeImageToRespose(Long id, HttpServletResponse response) {
        //store image in browser cache
        response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
        response.setHeader("Cache-Control", "max-age=2628000");

        //obtaining bytes from DB
        byte[] imageData = someEntityDao.getPhotoById(id);

        //Some conversion
        //Maybe to base64 string or something else
        //Pay attention to encoding (UTF-8, etc)
       
        //write result to http response
        try (OutputStream out = response.getOutputStream()) {
            out.write(convertedStringBytes);
        }
}