Update 20140702:
(but I'm marking one of the other answers as accepted instead of my own, as it got me halfway there, and to reward the effort)
It appears that setting a HTTP request header is not possible through links with <a href="...">
, and can only be done using XMLHttpRequest
.
However, the URL linked to is a file that should be downloaded (browser should not navigate to its URL), and I am not sure is this can be done using AJAX.
Additionally, the file being returned is a binary file, and AJAX is not intended for that.
How would one go about triggering a file download with a HTTP request that has a custom header added to it?
edit: fix broken link
i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.
WebApi method along with helper class:
Web.config file changes to allow sending file name in custom header.
Angular JS Service Part:
Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.
I'm adding another option. The answers above were very useful for me, but I wanted to use jQuery instead of ic-ajax (it seems to have a dependency with Ember when I tried to install through bower). Keep in mind that this solution only works on modern browsers.
In order to implement this on jQuery I used jQuery BinaryTransport. This is a nice plugin to read AJAX responses in binary format.
Then you can do this to download the file and send the headers:
The vars in the above script mean:
$('a.download-link')
.Try
html
js
jsfiddle http://jsfiddle.net/guest271314/SJYy3/
There are two ways to download a file where the HTTP request requires that a header be set.
The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.
The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.
The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.
Solution:
Note that I'm not using a raw
XMLHttpRequest
, and instead using ic-ajax, and should be quite similar to ajQuery.ajax
solution.Note also that you should substitute
text/bin
and.bin
with whatever corresponds to the file type being downloaded.The implementation of
FormatUtils.utf8toBase64
can be found herewith
download
attributesimply add
download
attribute to your linkfor example:
<a href="test.pdf" download="download">click to download file</a>
with
header
set the MIME-type of the file:
set_header('content-type', 'application/pdf')
then:
set_header('content-disposition', 'attachment; filename=output.pdf')
NOTE : instead
set_header
use appropriate command to change headers(this works for tornado)