How to create a dynamic file + link for download i

2019-01-10 11:19发布

This question already has an answer here:

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

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)?

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.

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

Is this feasible, if yes how?

3条回答
在下西门庆
2楼-- · 2019-01-10 12:04

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 demo and 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.

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

查看更多
戒情不戒烟
3楼-- · 2019-01-10 12:15

By appending a data URI to 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 script or jQuery plugin to do the encoding. Here is an example with static data:

jQuery('body').prepend(jQuery('<a/>').attr('href','data:text/octet-stream;base64,SGVsbG8gV29ybGQh').text('Click to download'))
查看更多
男人必须洒脱
4楼-- · 2019-01-10 12:25

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

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 supported very well.

Demo

Note: BlobBuilder seems to be deprecated. Refer to this answer to see how to use Blob instead of BlobBuilder. Thanks to @limonte for the heads up.

查看更多
登录 后发表回答