1.问题
在SpringBoot项目中上传到本地盘符中的图片无法直接访问到
<div>
<img src="file:\\D:\image\upload\1551922019301image.jpg">
</div>
2.解决办法
2.1.通过流读取
后台代码:
@RequestMapping(value ="/getImage")
public String createFolw(HttpServletRequest request, HttpServletResponse response) {
String path = request.getParameter("path");
// 取路径
FileInputStream fis = null;
OutputStream os = null;
try {
fis = new FileInputStream(path);
os = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024 * 8];
while ((count = fis.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return "personalCenter";
}
html代码:
<img alt="image" style="height:250px;width:400px;" src="/getImage?path=D:/image/upload/1551922019301image.jpg"/>
获取到图片
这样能够实现,但是如果访问量很大,需要多次读取流,所以不建议。
2.2通过配置虚拟目录读取
2.2.1在普通Java项目中
打开tomcat的conf文件夹,在server.xml中的标签内加入
<Context path="/upload/**" docBase="D:\image\upload" crossContext="true" reloadable="false" debug="0"/>
path是虚拟路径,docBase为真实路径
html代码:
<img alt="image" style="height:250px;width:400px;" src="/upload/1551922019301image.jpg"/>
2.2.2SpringBoot配置
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/image/upload/");
}
}
html代码:
<img alt="image" style="height:250px;width:400px;" src="/upload/1551922019301image.jpg"/>
页面展示:
上面的例子中拦截器拦截的请求和文件上传目录均是写死的,可将其放置application.yml配置文件 中, 便于修改。修改后代码如下所示:
- 配置文件
file:
staticAccessPath: /upload/**
uploadFolder: D:\\image\\upload
- 读取配置文件
@Component
@ConfigurationProperties(prefix = "file")
@Data
public class FileUploadProperteis {
//静态资源对外暴露的访问路径
private String staticAccessPath;
//文件上传目录
private String uploadFolder ;
}
- 给config注入配置文件的值
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private FileUploadProperteis fileUploadProperteis;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(fileUploadProperteis.getStaticAccessPath())
.addResourceLocations("file:" + fileUploadProperteis.getUploadFolder() + "/");
}
}