这是我的项目结构:
如您所见,我有images文件夹,我需要在该文件夹中传输产品图片。但是接下来的代码行:
MultipartFile productImage = newProduct.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
if(productImage != null && !productImage.isEmpty())
{
try
{
productImage.transferTo(new File(rootDirectory + "resources\\images\\" + newProduct.getProductId() + ".png"));
}
catch(Exception ex)
{
throw new RuntimeException("Product Image Saving failed", ex);
}
}
添加新产品后,产品图片将上传到: C:\ Users \ PC \ sts_ws \ spring-java-app \ module2 \ 1 \ webstore \ target \ webstore-1.0-SNAPSHOT \ resources \ images
但是我需要路径: C:\ Users \ PC \ sts_ws \ spring-java-app \ module2 \ 1 \ webstore \ src \ main \ webapp \ resources \ images
我不知道如何指向我想要的路径。
感谢您的帮助。
答案 0 :(得分:1)
您可以这样做,
ClassLoader resource = this.getClass().getClassLoader();
URL path = this.getClass().getResource("/resources/THEPATH ".png");
如果您想使用它,可以使用
File file = new File(path.getFile());