1. axios端
- 发送请求
- 获得response流文件
- 如果是文件则在页面中插入a标签
- 利用a标签实现浏览器的get下载
instance.get('url',{
params: {
path: 'xxx'
},
responseType: 'blob'
}).then(res => {
const { data, headers } = res
const fileName = headers['Content-Disposition'].replace(/\w+;filename=(.*)/, '$1')
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName );
document.body.appendChild(link);
link.click();
});
2. java端response暴露请求头Content-Disposition,方便前端获取
// 设置输出的格式
httpServletResponse.reset();
httpServletResponse.setContentType("application/octet-stream");
httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gbk"),"iso8859-1"));
3. 前端兼容方案
let blob = new Blob([response.data]);//response.data为后端传的流文件
let downloadFilename = xxx.docx;//设置导出的文件名
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//兼容ie浏览器
window.navigator.msSaveOrOpenBlob(blob, downloadFilename)
}else {
//谷歌,火狐等浏览器
let url = window.URL.createObjectURL(blob);
let downloadElement = document.createElement("a");
downloadElement.style.display = "none";
downloadElement.href = url;
downloadElement.download = downloadFilename;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(url);
}