[英]JavaScript: save base64 string as file
I have a base64 string, file type.我有一个 base64 字符串,文件类型。 File type can be image, text or even pdf.
文件类型可以是图像、文本甚至 pdf。 I need to show
download
link and when user clicks it should start downloading as expected file.我需要显示
download
链接,当用户点击它应该开始下载预期的文件。
Concisely, server sends me file as base64 string, and I need to save it as file on browser.简而言之,服务器将文件作为 base64 字符串发送给我,我需要将其保存为浏览器上的文件。 How can I save base64 string as file on browser?
如何在浏览器上将 base64 字符串保存为文件? It would be best if solution works on IE9 also.
如果解决方案也适用于 IE9,那将是最好的。
您可以使用download.js 。
download(base64String, filename, mimeType)
You can do this from js to download pdf.您可以从 js 执行此操作以下载 pdf。
Use:采用:
document.location = 'data:application/pdf;base64,' + base64String
Adapted from https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512f to work on Firefox.改编自https://gist.github.com/RichardBray/23decdec877c0e54e6ac2bfa4b0c512f以在 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(); }
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; Content-Disposition:附件; 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.如果您从服务器获取文件作为嵌入在 html 中的 base64 字符串,也许您可以跳过嵌入并简单地在您的服务器上嵌入文件的直接链接,让服务器将其提供给用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.