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。。。。

你可能感兴趣的:(java)