Upload and display images using thymeleaf and springboot
Solution 1
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"/>
Solution 2
Here is how I did it.
Step 1: Create a uploads folder in your project directory.
Step 2: Create ResourceConfig file
@Configuration
public class ResourceConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploads/**").addResourceLocations("file:uploads/");
}
}
Step 3: Add your html thymleaf
<img th:src="@{'/uploads/' + ${someobject.someAttribute}}"/>
Akshay Jadhav
Updated on June 13, 2022Comments
-
Akshay Jadhav almost 2 years
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.