JavaScript:将 base64 字符串保存为文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16996319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:42:52  来源:igfitidea点击:

JavaScript: save base64 string as file

javascriptfilebase64

提问by Ikrom

I have a base64 string, file type. File type can be image, text or even pdf. I need to show downloadlink 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.

我有一个 base64 字符串,文件类型。文件类型可以是图像、文本甚至 pdf。我需要显示download链接,当用户点击它应该开始按预期文件下载。
简而言之,服务器将文件作为 base64 字符串发送给我,我需要将其保存为浏览器上的文件。如何在浏览器上将 base64 字符串保存为文件?如果解决方案也适用于 IE9,那将是最好的。

回答by kerwal

You can use download.js.

您可以使用download.js

download(base64String, filename, mimeType)

回答by kerwal

You can do this from js to download pdf.

您可以从 js 执行此操作以下载 pdf。

Use:

利用:

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

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

回答by Nuno Ribeiro

Adapted from https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512fto work on Firefox.

改编自https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512f以在 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(); 
}

回答by Kirk B.

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"

Content-Disposition:附件;文件名="您的文件名.扩展名"

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.

如果您从服务器获取文件作为嵌入在 html 中的 base64 字符串,也许您可​​以跳过嵌入并简单地在您的服务器上嵌入文件的直接链接,让服务器将其提供给用户。

Related SO on Content-Disposition

关于内容处置的相关 SO