Issue
I have repository class where I want to store the image that is coming from MultipartFile to webapp/resources/images directory before adding the product details to the repository ?
@Override
public void addProduct(Product product) {
Resource resource = resourceLoader.getResource("file:webapp/resources/images");
MultipartFile proudctImage = product.getProudctImage();
try {
proudctImage.transferTo(new File(resource.getFile()+proudctImage.getOriginalFilename()));
} catch (IOException e) {
throw new RuntimeException(e);
}
listOfProducts.add(product);
}
my repository class is ResourceLoaderAware. I am getting fileNotFoundException, "imagesDesert.jpg" is the image I am trying to upload
java.io.FileNotFoundException: webapp\resources\imagesDesert.jpg (The system cannot find the path specified)
Solution
Finally I could able to fix this problem, we need not specify the file: prefix, and moreover by default resourceLoader.getResource()
will look for resources in the root directory of our web application, So no need of specifying the webapp
folder name. So finally the following code works for me
@Override
public void addProduct(Product product) {
MultipartFile proudctImage = product.getProudctImage();
if (!proudctImage.isEmpty()) {
try {
proudctImage.transferTo(resourceLoader.getResource("resources/images/"+product.getProductId()+".png").getFile());
} catch (Exception e) {
throw new RuntimeException("Product Image saving failed", e);
}
}
listOfProducts.add(product);
}
Answered By - Amuthan