之前写项目碰到一个需求,需要将主页图片做成可配置的,但是需要初始化图片,由于一些特殊环境所以将其做成静态放到项目里并打包到服务器上。
本人之前是直接读取路径来的,可是放到服务器上就会读取失败了,查了别人的博客才知道打包后这么个写法会失效的,所以采用流的形式读取是可以的。代码如下:
我是将资源图片放到了resources/templates下面的
@GetMapping("file/{path:.+}")
@SuppressFBWarnings
public void getFileResource(@PathVariable String path, HttpServletResponse response) throws IOException {
ClassPathResource classPathResource=new ClassPathResource("templates/"+path);
InputStream inputStream=classPathResource.getInputStream();
try (OutputStream os = response.getOutputStream()) {
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, count);
}
os.flush();
}finally {
inputStream.close();
}
log.info(path);
}