[英]How to get Project Path in a Java Spring Web App
這是我的項目結構:
如您所見,我有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
我不知道如何指向我想要的路徑。
謝謝你的幫助。
你可以做這樣的事情,
ClassLoader resource = this.getClass().getClassLoader();
URL path = this.getClass().getResource("/resources/THEPATH ".png");
如果您想要使用它,
File file = new File(path.getFile());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.