Malekai
Malekai

Reputation: 45

Force a File Download by either Ajax or Javascript

So i have a table listing files, each file's URL is stored as a data attribute on a button. On clicking a button I want to fire a Javascript/Ajax call that will download the file at the URL.

Now some caveats,

  1. The file needs to be downloaded via a download dialog or needs to just be added to the Browsers downloads as you would expect.
  2. The request needs to be able to take headers as this is a cross domain request.
  3. This needs to work on the main browsers (IE, Chrome, Firefox, Safari)

So far I have tried to use XMLHttpRequest:

e.preventDefault();
var csrftoken = getCookie('csrftoken');
var req = new XMLHttpRequest;
req.open("POST",$(this).data("url"));
req.setRequestHeader("MY HEADER", "HEADER VALUE;");
req.withCredentials = true;
req.send();

I've also tried Ajax GET request (which doesnt force the download) and using the Download attribute on an anchor tag (which doesnt accept headers).

Thanks

Upvotes: 1

Views: 575

Answers (2)

Lucas Tettamanti
Lucas Tettamanti

Reputation: 1820

You have to capture the url first, and then:

document.location = 'data:Application/octet-stream,' + encodeURIComponent("http://somedomain.com/somefile.some");

or

window.open("http://somedomain.com/somefile.some");

You don't need headers with this approach.

Upvotes: 0

Mike
Mike

Reputation: 894

Instead of using anchor tag, which is not cross-browser compliant (apparently, I didn't realize Microsoft was so slow to getting the HTML5 spec.. Not unexpected though)

We can utilize the iframe, to avoid redirect and to achieve this effect while maintaining cross-browser compliancy.

<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>

As long as the file isn't an .html or some kind of file that can be displayed via browser (.htm, .html, .xhtml, .aspx, etc) then it should download the file.

Upvotes: 4

Related Questions