【问题标题】:How to refresh a folder using java program in intellij / Eclipse? (Solved)如何在 intellij / Eclipse 中使用 java 程序刷新文件夹? (解决了)
【发布时间】:2020-04-09 10:14:32
【问题描述】:

我目前正在处理一个 Spring Boot 项目,同时上传图像,该图像是在 resources\static\images 中创建的,但是当我尝试显示图像时它没有显示。刷新文件夹后,它会反映出来。 这是我的代码:

// Method for uploading image.
    public void uploadImage(MultipartFile file) {
        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedOutputStream stream = null;
        try {
            stream = new BufferedOutputStream(new FileOutputStream(new File(
                    "D:\\New Language\\Spring Boot Demo\\employee_details\\src\\main\\resources\\static\\images"
                            + File.separator + file.getOriginalFilename())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            stream.write(bytes);
            stream.flush();
            stream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


// JSP Code For displaying image.   
    <div class="card-header border-0">
        <img src="/images/${emp.path}" alt="My Image">
    </div>                                                   

【问题讨论】:

  • “刷新文件夹”是什么意思?刷新浏览器?在浏览器的网络选项卡中,您能否查看图片是否再次下载或是否从缓存中提供?
  • @GreyFairer 不,我的意思是刷新文件夹。在网络标签中,它显示 Failed to load resource: the server responded with a status of 404 ()。但是当我去 IDE 并刷新文件夹时,图像就会显示在浏览器中。
  • 是的,2 分钟后我意识到真正的问题是您更新了 src/main/resources 而不是 target/classes(请参阅下面的答案)。解决了吗?
  • @GreyFairer 谢谢你的回答,但对我没有用。当我在资源外部和项目内部创建图像文件夹时,它对我有用。

标签: java spring spring-boot spring-mvc jsp


【解决方案1】:

您不应该在源文件夹中更改它。我不是 100% 确定,但我认为 IntelliJ 将使用 .../target/classes/ 作为类路径,并会在编译期间将文件复制到那里。 Spring Boot 将加载它在类路径中找到的任何 /static 文件夹。 所以你可以覆盖那里的文件而不是.../src/main/resources。这将一直有效,直到 IntelliJ 决定在编译期间覆盖它们或执行 mvn clean install

另外,如果您单独运行 spring boot 应用程序,资源将位于 jar 文件中,因此用作动态存储不是一个好主意。

最好单独创建一个动态存储文件夹,配置如下:

spring.resources.static-locations=classpath:/static/,file:/D:/...

当然,如果您在运行时更新该文件夹,它就不再是真正的静态了。还要检查https://www.baeldung.com/spring-mvc-static-resources

【讨论】:

    【解决方案2】:

    所以终于在 3 天后我找到了解决这个问题的方法。 由于resources\static\images\ 位置是关于静态内容的,并且通常将上传的(动态)内容保存在您的应用程序中是一个坏主意。所以我在resources 文件夹之外创建了一个文件夹,并放置了所有上传的(动态)图像文件。

    这是我解决这个问题的方法。 创建一个新类并尝试一下。

    @Configuration
    public class ResourceWebConfiguration implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(final ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/images/**").addResourceLocations("file:images/");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      相关资源
      最近更新 更多