将需要下载的资源放在resiurcs/static/中,然后下载下来
前端代码,使用thymeleaf模板为例index.html放在resources/templates中
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input type="button" onclick="down()" value="点击">
</body>
<script type="text/javascript">
function down(){
var url = window.encodeURI(this.axios.defaults.baseURL + '/ev/CommodityMaster/downloadTemp?fileName=D1120物资总清单导入模板.xlsx&token=' + localStorage.getItem("set_token"))
window.location.href = url
window.open("http://localhost:10000/download", '_blank')
// window.location.href = 'http://localhost:10000/download'
}
</script>
后台代码
/**
* 下载Excel模板
*/
@ApiOperation(value = "下载物资总清单导入模板", notes = "下载物资总清单导入模板", httpMethod = "POST")
@RequestMapping(value = "/downloadTemp", produces= MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadTemp(@RequestParam("fileName")String fileName,HttpServletRequest request, HttpServletResponse response) {
//定义文件名
// String fileName = "D1120物资总清单导入模板.xlsx";
try {
//获取资源文件
ClassPathResource classPathResource = new ClassPathResource("static/"+fileName);
//设置响应类型
response.setCharacterEncoding("UTF-8");
String type = new MimetypesFileTypeMap().getContentType(fileName);
response.setHeader("content-Type", type);
if(Objects.equals(getBrowser(request), "FF")){//如果是火狐,解决火狐中文名乱码问题
response.setHeader("Content-Disposition",
"attachment;fileName=" +new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
}else{
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
}
//获取资源文件输入流和httpServletResponse的输出流
try (InputStream inputStream =classPathResource.getInputStream(); ServletOutputStream servletOutputStream = response.getOutputStream()) {
//把资源文件的二进制流数据copy到response的输出流中
IOUtils.copy(inputStream, servletOutputStream);
//清除flush所有的缓冲区中已设置的响应信息至客户端
response.flushBuffer();
} catch (Exception e) {
//错误日志记录
log.error(e.getMessage());
}
} catch (Exception e) {
//自定义业务异常
throw new ProjectException("导出模板失败");
}
}
// 判断浏览器种类的方法
private String getBrowser(HttpServletRequest request) {
String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
if (UserAgent.contains("msie"))
return "IE";
if (UserAgent.contains("firefox"))
return "FF";
if (UserAgent.contains("safari"))
return "SF";
return null;
}
import org.apache.commons.io.IOUtils;
IOUtils.copy(inputStream, servletOutputStream);
地址https://mvnrepository.com/artifact/commons-io/commons-io/2.11.0