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; 
} 

我不确定它是否可以在生产中使用。基本上我得到了项目的绝对路径,然后追加我相对提取的路径。纠正我,如果我错了。