Springboot 项目目录下载模板文件工具类
//下载项目中的模板
@GetMapping(value = "/downloadTemplate")
public void downFrozenTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName = "模板.xlsx";
ServletOutputStream out;
response.setCharacterEncoding("UTF-8");
response.setContentType("content-type:octet-stream");
//文件在项目中的存放路径
String filePath = getClass().getResource("/templates/template1.xlsx").getPath();
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
}
filePath = URLDecoder.decode(filePath, "UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream inputStream = new FileInputStream(filePath);
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1) {
//写到输出流(out)中
out.write(buffer, 0, b);
}
inputStream.close();
if (out != null) {
out.flush();
out.close();
}
}
项目下模板存放位置