1.添加pom
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
2.方法
/**
* 根据文件名下载模板
*
* @param response
*/
@GetMapping("/template")
public void downloadTemplate(HttpServletRequest request,HttpServletResponse response) {
OutputStream os = null;
InputStream is = null;
String fileName = request.getParameter("fileName");
try {
InputStream inputStream = this.getClass().getResourceAsStream("/template/" + fileName);
File somethingFile = File.createTempFile("template", ".xlsx");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
inputStream.close();
}
InputStream in = new FileInputStream(somethingFile);
// 取得输出流
os = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName +".xlsx");
//复制
IOUtils.copy(in, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
System.out.println("下载文件失败," + e.getMessage());
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
}
}
}
3.前端调用
window.location.href = '/admin/employee/template?fileName=' + '得分记录表.xlsx'