springboot web 项目中页面无法回显上传的图片的问题

具体问题描述:
在图片上传以后再页面回显上传的图片,浏览器报错,如下:

Not allowed to load local resource:files:///D:/image/XXX.png

原因:

因为浏览器会保护,不允许加载在本地的文件,需要做一个虚拟路径即可解决问题.

解决办法:

注意:因为我是springboot web项目,所以这的方法适用于springboot web项目的。

1、既然要设置映射的虚拟路径,那么需要在application.yml中添加图片需要映射的路径:

springbootdo:
  uploadPath: D:/var/uploaded_files/
  imagePath: file:///D:/var/uploaded_files/image/

2、然后在程序实现映射的虚拟路径

/**
* @Description:    虚拟化本地文件或者图片访问路径
* @Author:         Cheney Master
* @CreateDate:     2018/8/1 13:56
* @Version:        1.0
*/
@Component
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {

    @Autowired
    Config config;

    /**
     * 虚拟化本地文件或者图片访问路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String mImagesPath = config.getImagePath();
        if (mImagesPath.equals("") || mImagesPath.equals("${springbootdo.imagesPath}")) {
            String imagesPath = WebConfigurer.class.getClassLoader().getResource("").getPath();
            if (imagesPath.indexOf(".jar") > 0) {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            } else if (imagesPath.indexOf("classes") > 0) {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            mImagesPath = imagesPath;
        }
        LoggerFactory.getLogger(WebConfigurer.class).info("imagesPath=" + mImagesPath);
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
        super.addResourceHandlers(registry);
    }

}
/**
* @Description:    配置路径
* @Author:         Cheney Master
* @CreateDate:     2018/8/1 15:30
* @Version:        1.0
*/

@Component
@ConfigurationProperties(prefix="springbootdo")
public class Config {
    //上传路径
    private String uploadPath;
    //图片路径
    private String imagePath;

    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

}

最后设置图片路径:

object.setImageUrl("/images/" + object.getImageUrl());

bingo。。。。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值