JavaScript: save base64 as file

I have a base64 string, file type. The file type can be an image, text, or even a PDF. I need to show the download link, and when the user clicks, he should start the download as the expected file.
In short, the server sends me the file as a base64 string, and I need to save it as a file in the browser. How to save base64 string as file in browser? It would be better if the solution worked on IE9 as well.

+10
source share
4 answers

You can use download.js .

 download(base64String, filename, mimeType) 
+9
source

You can do this from js to download pdf.

Using:

document.location = 'data:application/pdf;base64,' + base64String

+7
source

You get the desired effect (the web page showing the link, and when the user clicks the button, the save dialog opens) when the corresponding response headers are present, when the browser requests the resource:

Content-Disposition: attachment; file name = "yourfilename.extension"

If you get the file from the server as a base64 string embedded in your html, perhaps you can skip the attachment and simply insert a direct link to the file on your server, having a server serving it for the user.

Related SOs on Content-Disposition

+1
source

Adapted from https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512f to work in Firefox.

 downloadBase64File(contentBase64, fileName) { const linkSource = 'data:application/pdf;base64,${contentBase64}'; const downloadLink = document.createElement('a'); document.body.appendChild(downloadLink); downloadLink.href = linkSource; downloadLink.target = '_self'; downloadLink.download = fileName; downloadLink.click(); } 

0
source

All Articles