I am creating a Spring MVC Web Application in which I am uploading images from user and saving them at project folder in my drive (local laptop) and I am able to retrieve them successfully.
To save the images I am using the code:
MultipartFile productImage = product.getProductImage();
int Id= productService.addProduct(product);
path= Paths.get("C:/Users/oms/images/"+Id+".jpg");
//System.out.println(path.toString());
if(productImage!=null && !productImage.isEmpty()){
try {
productImage.transferTo(new File(path.toString()));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Product Image Saving Failed ",e);
}
}
Image is getting saved successfully.Now to retrieve them I am using the code:
<mvc:resources mapping="/images/**" location="file:///C:/Users/oms/images/" />
I am able to retrieve them successfully.
But this application works fine in local but If I deploy the war file in cloud It won't work because there is no C drive
and no users. I tried using the relative path to save the images in project folder but all failed.
I tried:
System.out.println("request.getContextPath()"+request.getContextPath());
System.out.println("request.getPathInfo()"+request.getPathInfo());
System.out.println("request.getPathTranslated()"+request.getPathTranslated());
System.out.println("request.getServletPath()"+request.getServletPath());
System.out.println("servletContext.getRealPath()"+servletContext.getRealPath("/"));
and all null except the getRealPAth()
.
servletContext.getRealPath()C:\Users\apache-tomcat-8.0.24\webapps\ROOT\
Obviously I can't save them in webapps folder because after restarting the server all images will be gone(deleted). How can I get the relative path to save images in the project folder so that when I am deploying this project in cloud it works fine?