Angular 8 - Parsing base64 to File

Viewed 17322

Im trying to convert a base64 file with this code

  new File([new Blob([BASE64FILE], {type: 'image/png'})],NAME,  {type: 'image/png'})

Something is wrong. When i send it to database have an incorrect format (not a image) and doesn't show anything.

So the question is: What is the right way to convert base64 to File?

2 Answers

I had similar issue back in the time. Anyway, this will work for you:

const base64 = '...';
const imageName = 'name.png';
const imageBlob = this.dataURItoBlob(base64);
const imageFile = new File([imageBlob], imageName, { type: 'image/png' });

and the function:

dataURItoBlob(dataURI) {
   const byteString = window.atob(dataURI);
   const arrayBuffer = new ArrayBuffer(byteString.length);
   const int8Array = new Uint8Array(arrayBuffer);
   for (let i = 0; i < byteString.length; i++) {
     int8Array[i] = byteString.charCodeAt(i);
   }
   const blob = new Blob([int8Array], { type: 'image/png' });    
   return blob;
}
\\ convert your image to base64
const imagePath = base64ToFile(this.croppedImage[this.selectedLinkId]);

\\ convert base64 to file
const imgFile = new File([imagePath], 'MyFileName.png');

\\ do whatever you want
this.sendFileToService(imgFile);
Related