问题描述
前端请求后台下载接口,返回数据流,然后下载下来的文件无法打开
前端下载相关代码
export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
解决方法
在请求拦截器里在请求之前加上responseType:'blob'或者在单个请求方法里指定返回类型
conf = conf.url?.includes('userTempDownload') ? Object.assign({},conf,{responseType:'blob'}) : conf;