storeDownload.ts
2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { AxiosInstance } from 'axios';
import type { ListingPageParams } from './storeTypes';
const DEFAULT_FILENAME = '门店列表.xlsx';
function exportFilename(disposition: string) {
const encoded = /filename\*\s*=\s*(?:"([^"]*)"|([^;]*))/i.exec(disposition);
const plain = /(?:^|;)\s*filename\s*=\s*(?:"([^"]*)"|([^;]*))/i.exec(disposition);
let filename = plain?.[1] ?? plain?.[2]?.trim() ?? DEFAULT_FILENAME;
if (encoded) {
try {
const value = (encoded[1] ?? encoded[2]).trim().replace(/^[^']*'[^']*'/, '');
filename = decodeURIComponent(value);
} catch {
// 不合法的 filename* 回退到普通文件名。
}
}
return filename.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim() || DEFAULT_FILENAME;
}
function invalidDownload(payload: unknown): Error {
let body = payload;
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch {
body = null;
}
}
if (body && typeof body === 'object' && 'message' in body && typeof body.message === 'string') {
return Object.assign(new Error(body.message), {
code: 'code' in body ? body.code : undefined,
data: 'data' in body ? body.data : undefined,
});
}
return new Error('导出响应不是可下载的文件');
}
/** 复用鉴权/签名拦截器,同时保留文件响应和 JSON 业务错误的不同处理。 */
export async function downloadStoreExport(http: AxiosInstance, params: ListingPageParams) {
let filename = DEFAULT_FILENAME;
let mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const response: unknown = await http.request({
method: 'GET',
url: '/store/listing/export',
params,
responseType: 'arraybuffer',
transformResponse: [
(raw: ArrayBuffer | string, headers) => {
filename = exportFilename(String(headers['content-disposition'] ?? ''));
mime = String(headers['content-type'] ?? mime);
// http 的 JSON 错误拦截需要原始文本,不能把 ArrayBuffer stringify 成 {}。
return /\bjson\b/i.test(mime) && typeof raw !== 'string'
? new TextDecoder().decode(raw)
: raw;
},
],
});
// 非 JSON 响应由共享拦截器包装为 { data, headers },先取出文件内容。
const payload =
response && typeof response === 'object' && 'headers' in response && 'data' in response
? response.data
: response;
if (!(payload instanceof ArrayBuffer)) throw invalidDownload(payload);
const blob = new Blob([payload], { type: mime });
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
link.hidden = true;
document.body.appendChild(link);
try {
link.click();
} finally {
link.remove();
// 让浏览器先消费下载链接,再释放其内存。
setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
}
}