Springboot加载静态图片

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_39895109/article/details/82979711

 java工具类:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by zhangj on 2018/07/31
 */
@Configuration
public class ShowImage extends WebMvcConfigurerAdapter {

    /**
     * 注入图片存放路径
     */
    @Value("${upload.path.prefix}")
    private String prefix;
    @Value("${upload.path.res}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
           //注:使用此种方法进行路径配置时,“file:D:/OTA/” 为正确路径地址 “file:D:/OTA”为错误路径地址,需以反斜杠结尾才可正确加载
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + prefix + "/");
        super.addResourceHandlers(registry);
    }
}

使用的是注入的方式,所以application中的配置:

upload:
  path:
    prefix: d:/app/share/data
    res: /upload/resource/

加载静态资源文件时使用springboot使用的方式,需注意点为拼接的路径需以反斜杠结尾,不然访问不到正确的路径地址,设置完成之后,即可进行访问。

如图片路径地址为:file:///D:/app/share/data/upload/resource/20180919/b104721b07d64501a6d24215dbc70207.bmp

需将 file:///D:/app/share/data 更改为 http://localhost:8765/images 即可成功访问。

猜你喜欢

转载自blog.csdn.net/weixin_39895109/article/details/82979711