springboot下载resources下的excel模板



jar文件中的资源,读取时必须使用流的方式

/**
* 下载导入模板
* @param request
* @param response
*/
@GetMapping("downloadTemplate")
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
InputStream in = null;
ServletOutputStream out = null;
String fileName = "导入模板.xlsx";

try {
in = this.getClass().getClassLoader().getResourceAsStream("import_template/template.xlsx");
response.setContentType("application/octet-stream");
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
out = response.getOutputStream();

int b = 0;
byte[] buffer = new byte[2048];
while ((b = in.read(buffer)) != -1) {
out.write(buffer, 0, b);
}

out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
}