uploader.ts 953 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import type { RequestClient } from '../request-client';
  2. import type { RequestClientConfig } from '../types';
  3. class FileUploader {
  4. private client: RequestClient;
  5. constructor(client: RequestClient) {
  6. this.client = client;
  7. }
  8. public async upload<T = any>(
  9. url: string,
  10. data: Record<string, any> & { file: Blob | File },
  11. config?: RequestClientConfig,
  12. ): Promise<T> {
  13. const formData = new FormData();
  14. Object.entries(data).forEach(([key, value]) => {
  15. if (Array.isArray(value)) {
  16. value.forEach((item, index) => {
  17. formData.append(`${key}[${index}]`, item);
  18. });
  19. } else {
  20. formData.append(key, value);
  21. }
  22. });
  23. const finalConfig: RequestClientConfig = {
  24. ...config,
  25. headers: {
  26. 'Content-Type': 'multipart/form-data',
  27. ...config?.headers,
  28. },
  29. };
  30. return this.client.post(url, formData, finalConfig);
  31. }
  32. }
  33. export { FileUploader };