spring boot 使用post方式实现excel模板下载功
2018-11-07 本文已影响160人
码农梦醒
spring boot实现以流的方式输出excel文件模板:
/**
* 模板下载
*
* @param response
* @throws Exception
*/
@RequestMapping(value = "/download/template")
@ApiOperation("模板下载")
public void downDivideTemplate(HttpServletResponse response) throws Exception {
String templateName = "convertTemplate.xls";
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
// 文件名
response.setHeader("Content-Disposition", "attachment;filename=" + templateName);
response.setHeader("Pragma", "no-cache");
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(new File("/Users/pan/Desktop/2003.xls"));
out = response.getOutputStream();
byte[] b = new byte[200];
int len;
while ((len = in.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (Exception e) {
in = null;
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
out = null;
}
}
}
}
前端使用axios以post方式,实现文件下载:
downloadByPost(url){
axios({ // 用axios发送post请求
method: 'post',
url: 'http://localhost:8080/test/download/template', // 请求地址
responseType: 'blob' // 表明返回服务器返回的数据类型
})
.then((resp) => { // 处理返回的文件流
if (!resp) {
return
}
let url = window.URL.createObjectURL(new Blob([resp.data])) // 这里一定要使用resp.data的内容,否则excel中的内容为: [object][object], 而非实际的模板内容
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xls')
document.body.appendChild(link)
link.click()
})
}