Search code examples
spring-mvcfile-uploadspring-bootthymeleaf

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.


Solution

  • 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"/>