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 }
标签:const,前端,reader,filename,link,error,封装,response,下载 From: https://www.cnblogs.com/huangxingquan/p/17577836.html