2

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

why var saveData and not a function?
It is a function
well then why use it as a variable?
As I know it has no big difference. Only the scope of the function change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.