Skip to content Skip to sidebar Skip to footer

Creating Download Prompt Using Purely Javascript

I have some text data (say var a = 'Hello World From Javascript';)in javascript variable in current window. I want to do the following through javascript- 1. open a new window and

Solution 1:

you can do that using JS & HTML5 features. Please find below a sample code.

var fileParts = ['Hello World From Javascript'];

        // Create a blob object.var bb = newBlob(fileParts,{type : 'text/plain'});

        // Create a blob url for this. var dnlnk = window.URL.createObjectURL(bb);

        var currentLnk = $('#blobFl').attr('href');

        // blobFl is the id of the anchor tag through which the download will be triggered.

        $('#blobFl').attr('href',dnlnk);
        $('#blobFl').attr('download','helloworld.txt');

        // For some reason trigger from jquery dint work for me.document.getElementById('blobFl').click();

Solution 2:

Triggering a file download without any server request

Unfortunately this is not something you can do with normal browser capabilities. Something like flash or a browser-specific plugin will get you what you need, but security limitations within javascript will not let you download arbitrary data created within the browser.

Also the 'data' url is not supported across all browser/version combinations. I am not sure if your users are constrained on what browser they are using or not but that may limit what you can do with that solution.

Source: Triggering a file download without any server request

Solution 3:

If you already have the file on the server (I make an ajax call to generate and save a PDF on the server) - you can do this

window.location.replace(fileUrl);

Solution 4:

No, Content-Disposition is a response header, it has to come from the server. I think you could do it with Flash but I wouldn't recommend it.

Solution 5:

Here's a clean, pure js version of @Rajagopalan Srinivasan's answer:

var fileParts = ["Hello World From Javascript"];
// The anchor tag to use.const blobLink = document.getElementById("blobLink");
// Create a blob object.var blob = newBlob(fileParts, { type: "text/plain" });

// Create a blob url for this.var blobUrl = window.URL.createObjectURL(blob);

blobLink.setAttribute("href", blobUrl);
blobLink.setAttribute("download", "helloworld.txt");
blobLink.click();
<a id="blobLink">Download</a>

Post a Comment for "Creating Download Prompt Using Purely Javascript"