You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot上传图片需重启才显示的问题求解

解决Spring Boot上传图片后无需重启即可显示的问题

问题分析

上传图片到src/main/resources/static/uploads/后无法实时显示,因为该目录属于classpath资源,仅在应用启动时被加载;上传到target/classes/static/uploads/能实时显示但属于编译输出目录,不适合作为持久化存储路径。

正确解决方案

1. 调整上传目录

修改FileUploadService中的上传路径,改为项目根目录下的独立文件夹(避免和classpath资源混淆):

public String uploadImage(MultipartFile multipartFile) throws IOException {
    String fileName = multipartFile.getOriginalFilename();
    // 改为项目根目录下的uploads文件夹
    Path uploadDirectory = Paths.get(System.getProperty("user.dir"), "uploads");
    
    // 确保目录存在,不存在则创建
    if (!Files.exists(uploadDirectory)) {
        Files.createDirectories(uploadDirectory);
    }

    try (InputStream inputStream = multipartFile.getInputStream()) {
        String path = UUID.randomUUID() + "-" + fileName;
        Path filePath = uploadDirectory.resolve(path);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        return path;
    } catch (IOException ioException){
        throw new IOException("Error saving uploaded file: " + fileName, ioException);
    }
}

2. 配置静态资源映射

创建一个WebMvcConfig类,正确配置资源处理器,同时保留原static目录的访问:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射/uploads/**请求到项目根目录的uploads文件夹
        String uploadPath = "file:" + System.getProperty("user.dir") + "/uploads/";
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(uploadPath)
                // 开发环境禁用缓存,确保实时加载
                .setCachePeriod(0);
        
        // 保留原static目录的资源映射
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }
}

3. 调整HTML中的资源路径

修改Thymeleaf的图片路径,使用绝对路径避免相对路径问题:

<div class="image">
    <img th:src="@{/uploads/{path}(path=${article.path})}" alt="">
</div>

为什么之前的addResourceHandlers失效?

之前的配置可能覆盖了默认的static目录映射,导致原有静态资源无法访问。上面的配置先添加自定义上传目录的映射,再保留原static目录的规则,确保两者都能正常工作。

额外说明

  • 生产环境可将上传目录配置为服务器外部路径(如/var/app/uploads/),避免项目打包时丢失上传文件;
  • 无需依赖Spring Boot DevTools的自动重启,上述配置已实现上传图片的实时访问。

内容的提问来源于stack exchange,提问作者aryszkij

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 03:20:52