Spring启动|将图片上传到资源中的相对路径

Spring Boot | Upload an image to relative path in resources

当我尝试将图像上传到资源内的项目文件夹时出现 "System can't find the path specified."。 这是我的项目结构:

|项目 |来源 |主要 |资源 |元-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 目录下的图像文件夹的确切路径是什么?

以下应该可以正常工作:

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

                    path);

简而言之 shell,请使用 "getClassLoader().getResourceAsStream()" 而不是 FileInputStream 或 FileOutputStream。

以下对我有用。 在 application.properties 中,我将路径字符串定义为:

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

这是我在 class 文件中的 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;
}

我不确定它是否适用于生产环境。基本上我得到项目的绝对路径,然后附加我相对提取的路径。如果我错了请纠正我。