2
0

upload-attachments.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import type { IAttachment } from '@growi/core';
  2. import { apiv3Get, apiv3PostForm } from '~/client/util/apiv3-client';
  3. import type { IApiv3GetAttachmentLimitParams, IApiv3GetAttachmentLimitResponse, IApiv3PostAttachmentResponse } from '~/interfaces/apiv3/attachment';
  4. import loggerFactory from '~/utils/logger';
  5. const logger = loggerFactory('growi:client:services:upload-attachment');
  6. type UploadOpts = {
  7. onUploaded?: (attachment: IAttachment) => void,
  8. onError?: (error: Error, file: File) => void,
  9. }
  10. export const uploadAttachments = async(pageId: string, files: File[], opts?: UploadOpts): Promise<void> => {
  11. files.forEach(async(file) => {
  12. try {
  13. const params: IApiv3GetAttachmentLimitParams = { fileSize: file.size };
  14. const { data: resLimit } = await apiv3Get<IApiv3GetAttachmentLimitResponse>('/attachment/limit', params);
  15. if (!resLimit.isUploadable) {
  16. throw new Error(resLimit.errorMessage);
  17. }
  18. const formData = new FormData();
  19. formData.append('file', file);
  20. formData.append('page_id', pageId);
  21. const { data: resAdd } = await apiv3PostForm<IApiv3PostAttachmentResponse>('/attachment', formData);
  22. opts?.onUploaded?.(resAdd.attachment);
  23. }
  24. catch (e) {
  25. logger.error('failed to upload', e);
  26. opts?.onError?.(e, file);
  27. }
  28. });
  29. };