admin-vben5/packages/effects/request/src/request-client/modules/uploader.ts
zhang 1616a06bfd
perf: 优化多文件上传入参是数组的情况 (#5757)
Co-authored-by: Jin Mao <50581550+jinmao88@users.noreply.github.com>
2025-03-25 10:26:19 +08:00

41 lines
953 B
TypeScript

import type { RequestClient } from '../request-client';
import type { RequestClientConfig } from '../types';
class FileUploader {
private client: RequestClient;
constructor(client: RequestClient) {
this.client = client;
}
public async upload<T = any>(
url: string,
data: Record<string, any> & { file: Blob | File },
config?: RequestClientConfig,
): Promise<T> {
const formData = new FormData();
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, item);
});
} else {
formData.append(key, value);
}
});
const finalConfig: RequestClientConfig = {
...config,
headers: {
'Content-Type': 'multipart/form-data',
...config?.headers,
},
};
return this.client.post(url, formData, finalConfig);
}
}
export { FileUploader };