目标:
实现:
import axios from 'axios';
import { getToken } from '@/utils/auth';
export const downloadZip = (url: string, params: any, fileName: string) => {
axios({
method: 'GET',
url: `${process.env.VUE_APP_BASE_API}${url}`,
headers: {
Authorization: 'Bearer ' + getToken(),
'Content-Type': 'application/x-www-form-urlencoded',
},
params: params,
responseType: 'blob',
}).then((res: any) => {
const blob = new Blob([res.data], { type: 'application/zip' }); // new一个二进制对象
const url = window.URL.createObjectURL(blob); // 转化为url
const link = document.createElement('a'); // 创建个a标签
link.href = url;
link.download = fileName; // 重命名
link.click();
URL.revokeObjectURL(url); // 释放内存
});
};
使用:
const documentsDownload = `rest/xxx/documentsDownload`;
private async handleDownload(file: string) {
const param = { fileWebPaths: file };
await downloadZip(documentsDownload, param, '附件');
}

这篇博客展示了如何使用axios库在JavaScript中实现文件的下载功能,特别是zip文件。通过设置请求头、参数及响应类型,结合Blob和URL.createObjectURL方法,实现了从API获取文件并触发浏览器下载。在实际应用中,该方法被用于处理`documentsDownload`接口的文件下载,参数包括文件路径和自定义文件名。
922

被折叠的 条评论
为什么被折叠?



