I have a base64 string, file type. File type can be image, text or even pdf. I need to show download
link and when user clicks it should start downloading as expected file.
Concisely, server sends me file as base64 string, and I need to save it as file on browser. How can I save base64 string as file on browser? It would be best if solution works on IE9 also.
Asked
Active
Viewed 5.9k times
23

Ikrom
- 4,785
- 5
- 52
- 76
4 Answers
17
Adapted from https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512f to work on Firefox.
function 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();
}

Luis Lobo
- 489
- 4
- 7

Nuno Ribeiro
- 2,487
- 2
- 26
- 29
-
There's a syntax error here: a "function" keyword is missing. – Anderson Green Sep 20 '20 at 17:55
-
4The file starts to download then I get a "Failed - Network error" – MadMac Jul 11 '22 at 00:52
-
@MadMac I had the same error. I had entered the wrong url. The correct format is "data:[fileMimeType];base64,[base64Content]" – danielevigi Jul 06 '23 at 06:38
16
You can use download.js.
download(base64String, filename, mimeType)
-
-
This opens a 'save file as' dialog for me. Can't it automatically save the image? – nclsvh Apr 25 '18 at 15:44
-
@nclsvh, this part is up to your browser. It may be configured to ask you any time or not. – ConductedClever Apr 13 '19 at 12:09
10
You can do this from js to download pdf.
Use:
document.location = 'data:application/pdf;base64,' + base64String

shapiro yaacov
- 2,308
- 2
- 26
- 39

kerwal
- 165
- 1
- 3
-
I think, in a SPA or a full ajax scenario, not opening another tab or not leaving current behavior is more suitable. – ConductedClever Apr 13 '19 at 12:10
-
This resulted in `Not allowed to navigate top frame to data URL: data:image/jpeg;base64, ...`. Unlike the OP, I tried to convert `base64String` into a jpeg file instead of PDF, which might cause this issue – Hiroki Oct 30 '22 at 08:49
1
You get the effect you desire (web page showing a link, and when user clicks, the save as dialog pops up) when the appropriate response headers are present when the browser requests the resource:
Content-Disposition: attachment; filename="yourfilename.extension"
If you're getting the file from the server as a base64 string embedded in your html, perhaps you can skip the embedding and simply embed a direct link to the file on your server, having the server serve it up to the user.