下载文件
@RequestMapping("/downloadTemplate")
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
//File template=new File(this.getClass().getResource("/reportTemplate").getPath()+"/企业产量导入模板.xlsx");
File template=new File("D:\\reportTemplate\\企业产量导入模板.xlsx");
if (template.exists()) {
// 取得文件名。
//String fileName = template.getName();
String fileName = URLEncoder.encode(template.getName(), "utf-8")
.replaceAll("\\+", "%20");
InputStream fis = null;
try {
fis = new FileInputStream(template);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");// 设置强制下载不打开
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + fileName);
response.setHeader("Content-Length", String.valueOf(template.length()));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
response.flushBuffer();
//fis.close();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
推荐使用这种方式,可以兼容本地和部署模式。
@RequestMapping("/downloadTemplate")
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
//File template=new File(this.getClass().getResource("/reportTemplate").getPath()+"/企业产量导入模板.xlsx");
//File template=new File("D:\\reportTemplate\\企业产量导入模板.xlsx");
//InputStream in = this.getClass().getResourceAsStream("/reportTemplate/企业产量导入模板.xlsx");
ClassPathResource resource = new ClassPathResource("reportTemplate/企业产量导入模板.xlsx");
InputStream in = resource.getInputStream();
try {
String fileName = URLEncoder.encode(Objects.requireNonNull(resource.getFilename()), "utf-8").replaceAll("\\+", "%20");
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");// 设置强制下载不打开
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + fileName);
byte[] b = new byte[1024];
int len;
while ((len = in.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
response.flushBuffer();
//fis.close();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}