Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload and display images using thymeleaf and springboot

This is my upload image code in Spring Boot:

String root = ctx.getRealPath("/");
File dir = new File(root + File.separatorChar + "images");
if (!dir.exists())
    dir.mkdir();

String path = dir.getAbsolutePath() + File.separatorChar
            + product.getProductName() + "."
            + file.getContentType().split("/")[1];
System.out.println(path);
File file1 = new File(path);
try {
    FileOutputStream fod = new FileOutputStream(file1);
    fod.write(file.getBytes());
    fod.close();
    product.setProductPicture("/images/" + product.getProductName()
            + "." + file.getContentType().split("/")[1]);
} catch (IOException e) {
    e.printStackTrace();
}

The uploading of files works fine, only problem with this code is that when i use ctx.getRealPath("/") it returns temporary location and when i restart the spring boot app i loose already existing files which was already uploaded as it creates a new temporary directory.

This causes some problem as i also have to display this pics on my site and now it returns "image not found error".

So I needed a solution which will allow me to upload files in a permanent location and serve files from there on the browser.

Note: I'm using thymeleaf for views.

like image 977
Akshay Jadhav Avatar asked Dec 11 '16 06:12

Akshay Jadhav


People also ask

How do you upload an image to Spring Boot Thymeleaf?

The displayUploadForm() method handles the GET request and returns the name of the Thymeleaf template to display to the user in order to let him import an image. The uploadImage() method handles the image upload. It accepts a multipart/form-data POST request on image upload and saves the image on the local file system.

How does Spring Boot Work With Thymeleaf?

Thymeleaf is a server-side Java-based template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. It is more powerful than JPS and responsible for dynamic content rendering on UI.


1 Answers

I found a solution for my problem. I created a new function which will only return bytes[] and sent as response body as follows:

@RequestMapping(value = "image/{imageName}")
@ResponseBody
public byte[] getImage(@PathVariable(value = "imageName") String imageName) throws IOException {

    File serverFile = new File("/home/user/uploads/" + imageName + ".jpg");

    return Files.readAllBytes(serverFile.toPath());
}

And in html <img alt="Image" th:src="@{image/userprofile}" width="250" height="250"/>

like image 56
Akshay Jadhav Avatar answered Oct 15 '22 18:10

Akshay Jadhav