文档流乱码:大部分的 vue 下载文档流 说用 new Blob();
但是也要例外,比如下图接口返回的文档流
res 如下:
此时,就不能用 const href = URL.createObjectURL(blob); 否则 接口的data返回的是什么,就仍是什么,pdf 和 word 都是乱码
vue中:
/** 下载 */
async downFun(item: dataType) {
// 方法 1
// axios.get(`${baseUrl}/zjhl/file/reportDownload?reportId=${item.uid}`, {
// responseType: 'blob', // 指定返回数据的格式为blob
// })
// .then((res) => {
// this.getOutExcel(item.fileName, res.data);
// })
// .catch(() => {
// this.$message.error('接口调用失败');
// });
// 方法 2
http.downloadGetBlob('/zjhl/file/reportDownload', { reportId: item.uid }).then((res: any) => {
this.getOutExcel(item.fileName, res.data);
});
}
/**
* fileName: 下载的文件名,带类型的.pdf/.doc/.docx...
* data: 是Blob类型的, 比如 res.data = Blob{size: 195151, type: 'application/pdf'}
* 如果不是Blob类型,那就需要转换成Blob类型,const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
* new Blob([data])用来创建URL的file对象或者blob对象
*/
getOutExcel(fileName: string, data: Blob) {
const a = document.createElement('a');
// 兼容不同浏览器的URL对象
const url = window.URL || window.webkitURL;
// 创建下载链接
a.href = url.createObjectURL(data);
// 命名下载名称
a.download = fileName;
// 点击触发下载
a.click();
// 下载完成进行释放
url.revokeObjectURL(a.href);
}
http.ts 中:
const http = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
downloadGetBlob(url: string, params: any) {
return servicse({
url,
method: 'get',
params,
responseType: 'blob',
// headers: { 'Content-Type': 'application/json;charset=utf-8' },
}).then((res) => res);
},
};
// 导出
export default http;