Javascript 如何在Javascript中创建动态文件+链接以供下载?

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

How to create a dynamic file + link for download in Javascript?

javascriptfiledynamicdownloadcreation

提问by Jér?me Verstrynge

Typically, HTML pages can have link to documents (PDF, etc...) which can be downloaded from the server.

通常,HTML 页面可以链接到可以从服务器下载的文档(PDF 等)。

Assuming a Javascript enabled webpage, is it possible to dynamically create a text document (for example) from within the user browser and add a link to download this document without a round trip to the server (or a minimal one)?

假设启用了 Javascript 的网页,是否可以从用户浏览器中动态创建文本文档(例如)并添加链接以下载此文档而无需往返服务器(或最少一次)?

In other word, the user would click on a button, the javascript would generate randoms numbers (for example), and put them in a structure. Then, the javascript (JQuery for example) would add a link to the page to download the result as a text file from the structure.

换句话说,用户会点击一个按钮,javascript 会生成随机数(例如),并将它们放入一个结构中。然后,javascript(例如 JQuery)会向页面添加一个链接,以将结果作为文本文件从结构中下载。

This objective is to keep all (or at least most) of the workload on the user side.

此目标是将所有(或至少大部分)工作负载保留在用户端。

Is this feasible, if yes how?

这是可行的,如果是,如何?

采纳答案by Nate Barr

By appending a data URIto the page, you can embed a document within the page that can be downloaded. The data portion of the string can be dynamically concatenated using Javascript. You can choose to format it as a URL encoded string or as base64 encoded. When it is base64 encoded, the browser will download the contents as a file. You will have to add a scriptor jQuery plugin to do the encoding. Here is an example with static data:

通过向页面附加数据 URI,您可以在可下载的页面中嵌入文档。字符串的数据部分可以使用 Javascript 动态连接。您可以选择将其格式化为 URL 编码字符串或 base64 编码。当它是 base64 编码时,浏览器会将内容下载为文件。您必须添加脚本或 jQuery 插件来进行编码。下面是一个静态数据的例子:

jQuery('body').prepend(jQuery('<a/>').attr('href','data:text/octet-stream;base64,SGVsbG8gV29ybGQh').text('Click to download'))

回答by ahuff44

Here's a solution I've created, that allows you to create and download a file in a single click:

这是我创建的一个解决方案,它允许您单击创建和下载文件:

<html>
<body>
    <button onclick='download_file("my_file.txt", dynamic_text())'>Download</button>
    <script>
    function dynamic_text() {
        return "create your dynamic text here";
    }

    function download_file(name, contents, mime_type) {
        mime_type = mime_type || "text/plain";

        var blob = new Blob([contents], {type: mime_type});

        var dlink = document.createElement('a');
        dlink.download = name;
        dlink.href = window.URL.createObjectURL(blob);
        dlink.onclick = function(e) {
            // revokeObjectURL needs a delay to work properly
            var that = this;
            setTimeout(function() {
                window.URL.revokeObjectURL(that.href);
            }, 1500);
        };

        dlink.click();
        dlink.remove();
    }
    </script>
</body>
</html>

I created this by adapting the code from this HTML5 demoand messing around with things until it worked, so I'm sure there are problems with it (please comment or edit if you have improvements!) but it's a working, single-click solution.

我通过改编这个 HTML5 演示中的代码并弄乱事情直到它起作用来创建它,所以我确定它存在问题(如果你有改进,请评论或编辑!)但它是一个有效的单击解决方案.

(at least, it works for me on the latest version of Chrome in Windows 7)

(至少,它适用于 Windows 7 中最新版本的 Chrome)

回答by Some Guy

A PDF file? No. A txtfile. Yes. With the recent HTML5 blobURIs. A very basic form of your code would look something like this:

一个PDF文件?不,一个txt文件。是的。使用最近的 HTML5 blobURI。代码的一个非常基本的形式如下所示:

window.URL = window.webkitURL || window.URL;
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
var file = new window.BlobBuilder(),
    number = Math.random().toString(); //In the append method next, it has to be a string
file.append(number); //Your random number is put in the file

var a = document.createElement('a');
a.href = window.URL.createObjectURL(file.getBlob('text/plain'));
a.download = 'filename.txt';
a.textContent = 'Download file!';
document.body.appendChild(a);

You can use the other methods mentioned in the other answers as a fallback, perhaps, since BlobBuilder probably isn't supportedvery well.

您可以使用其他答案中提到的其他方法作为后备,因为 BlobBuilder 可能不受支持

Demo

演示

Note:BlobBuilderseems to be deprecated. Refer to this answer to see how to use Blobinstead of BlobBuilder. Thanks to @limontefor the heads up.

注意:BlobBuilder似乎已被弃用。请参阅此答案以了解如何使用Blob代替BlobBuilder. 感谢@limonte 的提醒