【问题标题】:Spring Boot | Upload an image to relative path in resources弹簧靴 |上传图片到资源中的相对路径
【发布时间】:2017-05-09 11:43:01
【问题描述】:

我得到“系统找不到指定的路径。”当我尝试将图像上传到资源中的项目文件夹时。 这是我的项目结构:

|项目 |源 |主要 |资源 |META-INF.资源 |图片

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 目录下 images 文件夹的确切路径是什么?

【问题讨论】:

  • 你试过`ServletContext`了吗?
  • String path = context.getRealPath("resources/images" + imageName); 应该在你得到 ServletContext 后工作

标签: spring file-upload spring-boot image-uploading relative-path


【解决方案1】:

以下应该可以正常工作:

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

                    path);

简而言之,使用“getClassLoader().getResourceAsStream()”代替 FileInputStream 或 FileOutputStream。

【讨论】:

  • \META-INF.resources\images\ 对我的情况实际上不起作用。
  • 不是maven项目吗?
  • 是的。这是一个 Maven 项目。但我仍然面临“系统找不到指定的路径。”
  • 是的,您的权利我可以复制您的问题,我已经更改了答案,请尝试一下。
  • 感谢@Shaik Elias 的帮助。 IntelliJ 将项目目录显示为 META-INF.resources 作为单个目录名称。但是当我通过资源管理器进入项目结构时,META-INF 是一个单独的文件夹,而资源是它的子文件夹。你之前的建议对我有用。
【解决方案2】:

以下对我有用。 在 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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 2017-10-13
    • 2020-03-12
    • 2017-12-22
    • 2020-08-06
    • 2018-02-14
    • 2020-08-12
    • 2017-01-04
    相关资源
    最近更新 更多