无法解决“SpringBoot 图片上传无法马上显示,只能重启IDE后才生效”

配置WebMvcConfigurer无法解决“SpringBoot 图片上传无法马上显示,只能重启IDE后才生效”

网络上很多关于“SpringBoot 图片上传无法马上显示,只能重启IDE后才生效”的解决方案,基本是通过配置WebMvcConfigurer来解决,可参见配置WebMvcConfigurer
但是在配置完成后仍然无法解决这个问题,比较了我和博主的不同点,发现在目录结构上。
在这里插入图片描述
我的诉求是将图片保存到img下的newProd文件夹中,而博主相当于保存到img文件夹中,这时WebMvcConfigurer的配置应该如下所示:

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

/**
 * @description: webmvc配置资源映射路径
 * @create: 2022-06-10 13:57
 **/

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**").
                addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/resources/static/img/");
    }
}

而不是

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/newProd/**").             
        addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/resources/static/img/newProd/");
    }

控制器层再加上newProd子目录写入文件:

// 获取上传文件名
        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));
        // 定义上传文件保存路径
        String filePath = "C:/Users/Administrator/teatour/src/main/resources/static/img/";
        String path = filePath + "newProd/";
        //生成新的文件名称
        String newImgName = newProd.getId().toString() + suffixName;
        // 新建文件
        File filepath = new File(path, newImgName);
        // 判断路径是否存在,如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            // 写入文件
            file.transferTo(new File(path + File.separator + newImgName));
        } catch (IOException e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值