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

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)

Leave a Comment