0

I need to convert media into File type to upload with JS.

The below code gives me the correct File output when taking a picture from the BUILT IN camera on my computer:

 const convertToFile = (base64: string) => {
let arr = base64.split(","),
  mime = arr[0].match(/:(.*?);/)![1],
  bstr = atob(arr[1]),
  n = bstr.length,
  u8arr = new Uint8Array(n);

while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
const extension = mime.split("/")[1];
console.log(extension);
const fileName = new Date().getTime() + `.${extension}`;
return new File([u8arr], fileName, { type: mime });

};

Output => enter image description here

BUT when I try to convert a picture taken from my MOBILE PHONE CAMERA (runing it through the exact same code), this is the output that I get which is "corrupt".

enter image description here

**Please note I must convert this image to File, because of how the backend is structure I need to send it as a File (not as a Blob).

  • It looks like your mobile browser doesn't implement the File constructor properly(or at all). Use a Blob as a File is a Blob, whatever problems you are having using a Blob post it. – Musa Sep 16 '20 at 12:57
  • Wish I could help. Have you tried this approach? https://stackoverflow.com/questions/27553617/convert-blob-to-file – markoos Sep 16 '20 at 13:33
  • Thanks for your help. I indeed ended up just uploading the Blob and treating it in the backend. – Nahuel Tarricone Sep 18 '20 at 16:19

1 Answers1

0

The solution for this was to directly send a Blob and then treat it in the backend. For some reason the construction of a type File from my phone was not working properly