【发布时间】:2016-10-25 17:47:11
【问题描述】:
我正在创建一个 Spring MVC Web 应用程序,在该应用程序中我从用户上传图像并将它们保存在我的驱动器(本地笔记本电脑)的项目文件夹中,并且我能够成功检索它们。
要保存我使用代码的图像:
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);
}
}
图像已成功保存。现在要检索它们,我正在使用代码:
<mvc:resources mapping="/images/**" location="file:///C:/Users/oms/images/" />
我能够成功找回它们。
但是这个应用程序在本地运行良好,但是如果我在云中部署 war 文件它将无法运行,因为没有 C drive 并且没有用户。我尝试使用相对路径将图像保存在项目文件夹中,但都失败了。
我试过了:
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("/"));
以及所有null except the getRealPAth()。
servletContext.getRealPath()C:\Users\apache-tomcat-8.0.24\webapps\ROOT\
显然我无法将它们保存在 webapps 文件夹中,因为重新启动服务器后所有图像都将消失(删除)。如何获得将图像保存在项目文件夹中的相对路径,以便在云中部署此项目时可以正常工作?
【问题讨论】:
标签: spring jsp spring-mvc file-upload apache-commons-fileupload