JavaScript: save base64 string as file

扶醉桌前 提交于 2019-12-22 03:54:31

问题


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.


回答1:


You can use download.js.

download(base64String, filename, mimeType)



回答2:


You can do this from js to download pdf.

Use:

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




回答3:


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.

Related SO on Content-Disposition




回答4:


Adapted from https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512f to work on 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(); 
}


来源:https://stackoverflow.com/questions/16996319/javascript-save-base64-string-as-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!