axios 请求头部加上responseType='blob'
export const download = (data) => {
return request({
url:'请求地址',
method: 'post',
responseType:'blob',
data: data
})
}
后端代码响应头部需要设置Access-Control-Expose-Headers头部信息,把你需要获取的头部属性字段设置在这个值里面前端响应部分就可以获取,否则不可无法获取(多个用逗号分割),如下设置前端可以获取文件名字,
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(message, "UTF-8"));
response.setContentType("application/octet-stream");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
前端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);