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.
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.
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.
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With