ecstrema
ecstrema

Reputation: 691

Creating a file and triggering download in Javascript

I've got a really simple line in my code that should trigger the download of a file created on the go.

window.open(window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"})));

But for some reason, this does not work. A new window starts appearing, and then suddenly disappears.

Any clue why this doesn't work?

EDIT: If I call

`window.location = window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"}));`

It opens the file. But nothing was downloaded.

Upvotes: 2

Views: 506

Answers (1)

dilusha_dasanayaka
dilusha_dasanayaka

Reputation: 1441

Try this solution

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);

    return function () {
         var data = "Your data...........",
             fileName = "filename";
            blob = new Blob(data, {type: "text/plain"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.text = "download file";
        window.URL.revokeObjectURL(url);
    };
}());

this will create new <a> element. You can download the file by clicking it.

This needs HTML 5 support and for more options, check answers for this question.

Upvotes: 4

Related Questions