fetch:
fetch('your-api-url')
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'example.pdf'; // 设置下载的文件名
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
});
axios:
async function downloadFile(url: string, fileName: string) {
try {
// 发起请求,获取文件流
const response = await axios({
url,
method: 'GET',
responseType: 'blob' // 指定响应类型为 blob
});
// 创建一个 Blob 对象
const blob = new Blob([response.data], { type: 'application/octet-stream' });
// 创建一个 URL 对象
const urlObject = window.URL.createObjectURL(blob);
// 创建一个隐藏的 <a> 元素
const link = document.createElement('a');
link.href = urlObject;
link.download = fileName; // 设置下载的文件名
// 将 <a> 元素添加到 DOM 中
document.body.appendChild(link);
// 触发点击事件
link.click();
// 移除 <a> 元素
document.body.removeChild(link);
// 释放 URL 对象
window.URL.revokeObjectURL(urlObject);
} catch (error) {
console.error('下载文件时出错:', error);
}
}
// 调用函数下载文件
downloadFile('https://example.com/api/download', 'example.pdf');
关键点
– responseType: ‘blob’:指定 axios 请求的响应类型为 blob,这样可以正确处理二进制数据。
– Blob 对象:用于表示不可变的原始数据,可以用来创建文件流。
– window.URL.createObjectURL:创建一个指向 Blob 的 URL,这个 URL 可以被 a 元素使用。
– a 元素:创建一个隐藏的 a 元素,设置其 href 属性为创建的 URL,并触发点击事件以开始下载。
– document.body.appendChild 和 document.body.removeChild:将 a 元素临时添加到 DOM 中,然后移除,以确保点击事件能够触发。
– window.URL.revokeObjectURL:释放创建的 URL 对象,避免内存泄漏。
通过以上步骤,你可以使用 axios 实现从后端接口下载文件流并保存到本地的功能。
注意点
后端响应头设置:
– 确保后端返回的 Content-Type 是正确的,例如对于 PDF 文件应该是 application/pdf。
– 检查 Content-Disposition 是否正确设置了文件名和编码方式,例如 attachment; filename*=UTF-8’'example.pdf。
前端处理 Blob 数据:在创建 Blob 对象时,确保传递了正确的 MIME 类型。
字符编码:确保前后端使用的字符编码一致,通常是 UTF-8。