1、下载 ‘Content-Type‘: ‘application/octet-stream‘ 的文件
当后端返回的响应头中 Content-Type 为 application/octet-stream 时,表示这是一个二进制流文件,浏览器无法直接展示,需要前端处理后下载到本地。
通过请求获取二进制数据,将数据转换为 Blob 对象,创建临时 URL 并触发下载,释放内存资源。
export const downloadFile = (data: any) => {return request({url: API.DOWNLOAD_URL + `?type=${data.type}`,method: 'post',responseType: 'blob', // 必须设置headers: {'Content-Type': 'application/octet-stream'}})
}
const download = async () => {let data = { type: "gender" };let result: any = await downloadFile(data); // {size: 9030, type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}let blob = new Blob([result], {// {size: 9030, type: 'application/vnd.ms-excel;charset=utf-8'}type: "application/vnd.ms-excel;charset=utf-8",});let fileName = "性别文件";//createObjectURL是JavaScript中一个非常有用的函数,它可以将Blob、File//等二进制文件转换为浏览器可以直接显示的URL地址,从而方便进行展示、//下载等操作。let url = URL.createObjectURL(blob); //blob:http://localhost:5173/cc119d4d-56f8-4d5f-9f20-ef4a9578d763const a = document.createElement("a");a.download = fileName;a.href = url;document.body.appendChild(a);a.click();document.body.removeChild(a);window.URL.revokeObjectURL(url);
};
2、
export function getFileURL(query) {return request({url: '/admin/fileCenter/getFileURL',method: 'get',params: query})
}
async download(id) {let data = {fileId: id,};await getFileURL(data).then((res) => {if (res.code == 0) {const a = document.createElement("a");const url = res.data.url;// 这里是将url转成blob地址,fetch(url).then((resFile) => resFile.blob()).then((blob) => {// 将链接地址字符内容转变成blob地址a.href = URL.createObjectURL(blob);a.download = res.data.fakeFileName; // 下载文件的名字// a.download = url.split('/')[url.split('/').length -1] // // 下载文件的名字document.body.appendChild(a);a.click();});} else {this.$message.error(res.message);}});},
参考https://blog.csdn.net/wusandaofwy/article/details/148905382