javascript Base64 编码/解码和下载 URL 中生成的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10755749/
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-26 10:56:11  来源:igfitidea点击:

Base64 encode/decode and download content generated in URL

javascriptbase64

提问by seedg

I am generating a string through JavaScript and I need to download it to a text file with a predefined dynamic filename. This way there will be no room for error by employees.

我正在通过 JavaScript 生成一个字符串,我需要将它下载到一个具有预定义动态文件名的文本文件中。这样员工就不会犯错。

This is obviously not possible in JavaScript due to security issues. However, from what I have read it should be possible with base64 encoding.

由于安全问题,这在 JavaScript 中显然是不可能的。但是,从我读到的内容来看,base64 编码应该是可能的。

I managed to encode the string and open a url with the decoded data. The string has been decoded successfully in this URL. The format is as follows:

我设法对字符串进行编码并使用解码后的数据打开一个 url。此 URL 中的字符串已成功解码。格式如下:

var data = 'data:text/plain;base64,'+L_EncodedData;
document.location = data;

I need to open a file dialog with the decoded data so the employees can download the content generated in this URL.

我需要打开一个包含解码数据的文件对话框,以便员工可以下载此 URL 中生成的内容。

Any help?

有什么帮助吗?

Many thanks in advance

提前谢谢了

回答by Grinn

If you're still looking for an answer to this, check out my answer here. This is how I would adapt it for your needs.

如果您仍在寻找答案,请在此处查看我的答案。这就是我将如何适应您的需求。

// Convert the Base64 string back to text.
var txt = atob(data.reportBase64Bytes);

// Blob for saving.
var blob = new Blob([byteString], { type: "text/plain" });

// Tell the browser to save as report.txt.
saveAs(blob, "report.txt");

If you use this, make sure you grab the polyfills that I mention in the other post.

如果您使用它,请确保您使用了我在另一篇文章中提到的 polyfill。

回答by user1520762

This block is fixed.

这个块是固定的。

window.OpenWindowForBase64 = function(url, callback) {
    var image = new Image();
    image.src = url;
    var w = window.open("");
    w.document.write(image.outerHTML);
    if (callback) {
        callback(url);
    }
}