踩坑
发现前几天写的导出文件功能测试还好好的, 今天导出的文件就都变成打不开的了
一路从请求排查到响应,试了各路大神的文件导出功能写法,发现还是打不开,最后惊奇的发现request对象被mockjs包装了的原因
Mockjs处理过的request
原生的request
后端响应文件流导出文件方法
方法一:
-
安装插件
npm i file-saver -
导入
import FileSaver from "file-saver"export function exportWrapper(apiPath, postData) { return request.post('/fog' + apiPath, postData, { responseType: 'blob',//发送请求时设置响应类型 }); }request.interceptors.response.use((response) => { if (response.headers['content-type'].indexOf('application/vnd.ms-excel') > -1) { return response; //响应拦截器判断返回的content-type,符合要求不做任何处理, 直接返回 } })
exportFn(){
const response = await exportFile(this.currentRow.id);//请求得到文件流数据
const arr = response.headers["content-disposition"].split("=");
const fileName = arr[arr.length - 1];
const blob = new Blob([response.data], {
type: response.headers['content-type'],
});
FileSaver.saveAs(blob, fileName);
}
方法二:
- 发送请求时设置响应类型
- 返回原生响应
exportFn(){
let blobObj = new Blob([response.data]); // 新建 Blob 对象
let url = window.URL.createObjectURL(blobObj); // 创建 URL 对象
let downloadLink = document.createElement('a'); // 创建 a 元素
downloadLink.style.display = 'none'; // 隐藏链接
downloadLink.href = url; // 添加下载地址
document.body.appendChild(downloadLink); // 添加 a 元素
downloadLink.click(); // 点击下载
document.body.removeChild(downloadLink); // 移出 a 元素
}
\