Type 'DocumentUpload' is not assignable to type 'BlobPart'

2.4k views Asked by At

I was originally passing a FileList to my function therefore new Blob([file]) would work. but now I have to extract some valid file types and convert them for posting to the server but TypeScript complains that Type 'DocumentUpload' is not assignable to type 'BlobPart'.

I tried to cast the file (which is no longer type File but DocumentUpload):

  const doUpload = async (fileList: DocumentUpload[]) => {

    const requests = fileList.map(async file => {
      const formData = new FormData();
      const blob = new Blob([file as BlobPart]);
      formData.append(file.name, blob);

      return axios
        .post(
          'https://jsonplaceholder.typicode.com/posts',
          {
            policyReference: referenceQuery,
            filename: file.name,
            fileType: file.type,
            lastModified: file.lastModified,
            ...formData,
          },
          {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
            onUploadProgress(progressEvent: ProgressEvent) {
              handleUploadProgress(progressEvent, file.lastModified);
            },
          }
        )
        .catch(e => handleUploadError(file.lastModified));
    });
    Promise.allSettled(requests).then(p => setIsProcessDisabled(false));
  };

DocumentUpload interface:

export interface DocumentUpload {
  lastModified: number;
  name: string;
  type: string;
  status: DocumentUploadStatus;
  progress: number;
}

How can I convert the file into a Blob here?

1

There are 1 answers

0
RyanP13 On

I solved it rather than casting I constructed a new file from the object properties:

  const f = new File([file.name], file.name, {
    type: file.type,
    lastModified: file.lastModified,
  });