axios部分
export const download = (data) => {
return request({
url:'请求地址',
method: 'post',
responseType:'blob', //设置响应类型
data: data
})
}
前端js处理响应部分进行blob字节处理下载文件
const filename = res.headers["content-disposition"];
const blob = new Blob([res.data]);
var downloadElement = document.createElement("a");
var href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = decodeURIComponent(filename.split("filename=")[1]);
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
后端下载
//设置响应头内容类型
response.setContentType("application/octet-stream");
//添加响应头,带上文件名
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("端口导入模板.xlsx", "UTF-8"));
//暴露新加的响应头,不然前端获取不到
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//获取文件名,只能取流,按这种方式取文件名,打成jar包之后取不到
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mb/zcgl/端口导入模板.xlsx");
//流拷贝
InputStream is = new BufferedInputStream(resourceAsStream);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
byte[] bytes = new byte[1024];
int num = 0;
while ((num = is.read(bytes)) != -1) {
os.write(bytes, 0, num);
os.flush();
}