0

我得到「系統找不到指定的路徑」。當我嘗試上傳一個圖像到資源內的項目文件夾。 這裏是我的項目結構:Spring Boot |將圖像上傳到資源中的相對路徑

|工程 | SRC |主 |資源 | META-INF.resources |圖片

Project Structural Hierarchy can be seen here in the image format.

我已經定義了路徑

String path = "\\resources\\images\\" + imageName; File file = new File(path); 
    try { 
     InputStream is = event.getFile().getInputstream(); 
     OutputStream out = new FileOutputStream(path); 
     byte buf[] = new byte[1024]; 
     int len; 
     while ((len = is.read(buf)) > 0) 
      out.write(buf, 0, len); 
     is.close(); 
     out.close(); 
    } catch (Exception e) { 
     System.out.println(e); 
    } 

什麼是META-INF.resources director下images文件夾的確切路徑ÿ?

+0

你試過'ServletContext'嗎? – fiskra

+0

'String path = context.getRealPath(「resources/images」+ imageName);'應該在你得到'ServletContext'後應該可以工作 – fiskra

回答

0

以下應很好地工作:

//App.java 
    String path = "\\META-INF.resources\\images\\" + imageName; 
    InputStream is = App.class.getClassLoader().getResourceAsStream(

        path); 

在堅果殼,使用 「getClassLoader()的getResourceAsStream()」,而不是的FileInputStream或FileOutputStream中。

+0

\ META-INF.resources \ images \實際上並不適用於我的情況。 –

+0

這不是一個maven項目嗎? –

+0

是的。這是一個maven項目。但我仍然面臨着「系統找不到指定的路徑」。 –

0

以下爲我工作。 在application.properties我定義我的路徑字符串爲:

image.path = src/main/resources/META-INF/resources/images/uploads/

這裏是一個類文件我uploadImage功能。

@Autowired 
private Environment environment; 

public String uploadImg(FileUploadEvent event, String imagePrefix) { 

    String path = environment.getProperty("image.path"); 

    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss"); 
    String name = fmt.format(new Date()) 
      + event.getFile().getFileName().substring(
      event.getFile().getFileName().lastIndexOf('.')); 
    name = String.format("%s%s" ,imagePrefix ,name); 
    String finalPath = String.format("%s%s" ,path ,name); 
    System.out.println("image is going to save @ " +finalPath); 

    File file = new File(finalPath).getAbsoluteFile(); 

    try { 
     InputStream is = event.getFile().getInputstream(); 
     OutputStream out = new FileOutputStream(file); 
     byte buf[] = new byte[1024]; 
     int len; 
     while ((len = is.read(buf)) > 0) 
      out.write(buf, 0, len); 
     is.close(); 
     out.close(); 
    } catch (Exception e) { 
     System.out.println(e); 
    } 
    return name; 
} 

我不確定它是否可以在生產中使用。基本上我得到了項目的絕對路徑,然後追加我相對提取的路徑。糾正我,如果我錯了。