Reputation: 45
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,
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
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
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