0

When I try to save on Angular a base64 file with this format :

// receivedFile.file = "data:image/jpeg;base64,/9j/4AAQSkZJR..."

var a = document.createElement('a');
const blob = new Blob([receivedFile.file], {type: receivedFile.infos.type});
a.href = URL.createObjectURL(blob);
a.download = receivedFile.infos.name;
a.click(); 

This code give me a corrupted file, how can I do ?

4 Answers4

3

In Angular (and in general) I use file-saver :

import { saveAs } from 'file-saver';
const blob = new Blob([receivedFile], {type: receivedFile.infos.type});
FileSaver.saveAs(blob, receivedFile.infos.name);

Also, try to remove the data:image/jpeg;base64, part of the string :

receivedFile.file.replace("data:image/jpeg;base64," , "")
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
2

Here is the code which converts base64 to downloadable file format in angular.

If for example your file type is csv, then below is the code snippet

downloadFile(base64:any,fileName:any){
const src = `data:text/csv;base64,${base64}`;
const link = document.createElement("a")
link.href = src
link.download = fileName
link.click()

link.remove()
}

//calling above function with some sample base64 data
downloadFile("c21hbGxlcg==","demo.csv")

Note: The file type can be anything you can give based on the need(In src of above code snippet).Here I am considering the csv file as example.

So by calling this above function You can download the resultant file will be downloaded from browser.

sateesh
  • 46
  • 4
0

To resolve this problem :

  • Removed data:image/jpeg;base64 from the receivedFile.file.
  • Use the function atob(), const byteCharacters = atob(receivedFile.file);
  • Then make the blob const blob = new Blob([byteCharacters], {type: this.receivedFile.infos.type});
0

try this

const downloadLink = document.createElement('a');
const fileName = 'sample.pdf';
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
Olagoke Mills
  • 67
  • 5
  • 8