前端文件下载方法封装

 1 export const downloadFileAxios = (fileUrl) => {
 2     axios({
 3         url: fileUrl,
 4         method: 'GET',
 5         responseType: 'blob',
 6     }).then((response) => {
 7             const contentDisposition = response.headers['content-disposition'];
 8             let filename = '';
 9             if (contentDisposition) {
10                 const filenameMatch = contentDisposition.match(/filename\*?=['"]?(?:UTF-\d['"]*)?([^;\r\n"']*)['"]?;?/);
11                 if (filenameMatch != null) {
12                     filename = decodeURIComponent(filenameMatch[1]);
13                 }
14             }
15             if (!filename) {
16                 return Promise.reject(response)
17             }
18             const url = window.URL.createObjectURL(new Blob([response.data]));
19             const link = document.createElement('a');
20             link.href = url;
21             link.setAttribute('download', filename);
22             document.body.appendChild(link);
23             link.click();
24             window.URL.revokeObjectURL(url);
25             Message.success("文件下载成功")
26         }).catch((error) => {
27             if (error.data) {
28                 // 转换 Blob 为 JSON
29                 let reader = new FileReader();
30                 reader.onload = function() {
31                     let responseJson = JSON.parse(reader?.result as string);
32                     Message.error(responseJson.msg);
33                 };
34                 reader.readAsText(error.data);
35             } else {
36                 Message.error("文件下载失败")
37             }
38         });
39 }

 

posted @ 2023-07-24 17:27  十盏  阅读(23)  评论(0编辑  收藏  举报