let filename = '';
const anaExport = (data) => {
return fetch('/export', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
// 请求头设置:比如说下面这个是给后台传递token信息
'token': window.localStorage.getItem('token') || ''
},
// 给后台传递的数据,这个得自己手动json序列化它
body: JSON.stringify(data)
}).then(res => {
// 响应头里面获取文件信息,注意:如果发现文件名字不对,看看这个响应头字段
const contentDisposition = res.headers.get("content-disposition")
if (res.status !== 200 || !contentDisposition) return message.error('导出失败');
// 解码,下载后的文件名字
filename = decodeURIComponent(contentDisposition?.split('=')?.[1] || '')
const reader = res.body?.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader?.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
push();
})
}
push();
}
});
})
.then(stream => {
// content-type 这个改成接口响应头的content-type就行了。浏览器控制台network(网络)中的response ...(响应标头)里面的content-type
const res = new Response(stream, { headers: { "Content-Type": "application/zip" }});
res.blob().then((result) => {
const file = new Blob([result]);
// 把二进制数据生成对应的url地址(缓存地址)
const objectUrl = URL.createObjectURL(file)
// 以下为常规操作:创建 a 标签,然后进行下载文件
const a = document.createElement("a")
document.body.appendChild(a)
a.style = "display: none"
a.href = objectUrl
a.download = filename.replace(/['\"']/img, '')
a.click()
window.URL.revokeObjectURL(objectUrl)
document.body.removeChild(a);
// ------------------------
})
})
.catch(e => {
console.error(e);
});
}
下载文件(fetch)(js)
于 2023-03-28 11:50:54 首次发布