blob: 5d56cdafc88b3ee4357d2deb4fa34d220b972153 [file] [log] [blame]
86133aaa3f5d2025-04-20 21:33:29 +08001import { request } from '@umijs/max';
2
3const mimeMap = {
4 xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
5 zip: 'application/zip',
6};
7
8/**
9 * 解析blob响应内容并下载
10 * @param {*} res blob响应内容
11 * @param {String} mimeType MIME类型
12 */
13export function resolveBlob(res: any, mimeType: string) {
14 const aLink = document.createElement('a');
15 const blob = new Blob([res.data], { type: mimeType });
16 // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
17 const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
18 // console.log(res);
19 const contentDisposition = decodeURI(res.headers['content-disposition']);
20 const result = patt.exec(contentDisposition);
21 let fileName = result ? result[1] : 'file';
22 fileName = fileName.replace(/"/g, '');
23 aLink.style.display = 'none';
24 aLink.href = URL.createObjectURL(blob);
25 aLink.setAttribute('download', fileName); // 设置下载文件名称
26 document.body.appendChild(aLink);
27 aLink.click();
28 URL.revokeObjectURL(aLink.href); // 清除引用
29 document.body.removeChild(aLink);
30}
31
32export function downLoadZip(url: string) {
33 request(url, {
34 method: 'GET',
35 responseType: 'blob',
36 getResponse: true,
37 }).then((res) => {
38 resolveBlob(res, mimeMap.zip);
39 });
40}
41
42export async function downLoadXlsx(url: string, params: any, fileName: string) {
43 return request(url, {
44 ...params,
45 method: 'POST',
46 responseType: 'blob',
47 }).then((data) => {
48 const aLink = document.createElement('a');
49 const blob = data as any; // new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
50 aLink.style.display = 'none';
51 aLink.href = URL.createObjectURL(blob);
52 aLink.setAttribute('download', fileName); // 设置下载文件名称
53 document.body.appendChild(aLink);
54 aLink.click();
55 URL.revokeObjectURL(aLink.href); // 清除引用
56 document.body.removeChild(aLink);
57 });
58}
59
60
61export function download(fileName: string) {
62 window.location.href = `/api/common/download?fileName=${encodeURI(fileName)}&delete=${true}`;
63}