1.问题
在SpringBoot项目中上传到本地盘符中的图片无法直接访问到
<div>
<img src="file:\\D:\image\upload\1551922019301image.jpg">
</div>
- 1
- 2
- 3
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";
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
html代码:
<img alt="image" style="height:250px;width:400px;" src="/getImage?path=D:/image/upload/1551922019301image.jpg"/>
- 1
获取到图片
这样能够实现,但是如果访问量很大,需要多次读取流,所以不建议。
2.2通过配置虚拟目录读取
2.2.1在普通Java项目中
打开tomcat的conf文件夹,在server.xml中的标签内加入
<Context path="/upload/**" docBase="D:\image\upload" crossContext="true" reloadable="false" debug="0"/>
- 1
path是虚拟路径,docBase为真实路径
html代码:
<img alt="image" style="height:250px;width:400px;" src="/upload/1551922019301image.jpg"/>
- 1
2.2.2SpringBoot配置
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/image/upload/"); }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
html代码:
<img alt="image" style="height:250px;width:400px;" src="/upload/1551922019301image.jpg"/>
- 1
页面展示:
上面的例子中拦截器拦截的请求和文件上传目录均是写死的,可将其放置application.yml配置文件 中, 便于修改。修改后代码如下所示:
- 配置文件
file:
staticAccessPath: /upload/**
uploadFolder: D:\\image\\upload
- 1
- 2
- 3
- 读取配置文件
@Component @ConfigurationProperties(prefix = "file") @Data public class FileUploadProperteis {
//静态资源对外暴露的访问路径 private String staticAccessPath; //文件上传目录 private String uploadFolder ;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 给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() + "/"); }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
参考:https://www.cnblogs.com/zuidongfeng/p/8859235.html
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
</div>