SpringBoot中通过接口下载resources下的文件
解决的问题
- 当项目打成jar包进行部署时,一些示例文件放在resources目录下,提供接口供用户访问下载
文件存放位置

接口实现
@RequestMapping("/downloadExampleExcel")
@ResponseBody
public void downloadExampleExcel(HttpServletResponse response) {
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
Resource resource = new DefaultResourceLoader().getResource("classpath:example_add_infos.xls");
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + "example_add_infos.xls");
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
servletOutputStream = null;
}
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}