alexanoid alexanoid - 9 days ago 8
jQuery Question

JavaScript get file from server

I have a following server endpoint that expects X-DOWNLOAD:yes request header parameter:

GET/POST example.com/download


If X-DOWNLOAD:yes is present server returns file to client. If no - redirects user to another page.

How to make a JavaScript call from client in order to get a file(set X-DOWNLOAD:yes parameter) - show browser Save dialog ?

Answer

To add headers to the request do something like this:

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "X-Download":"yes",
    }
    //OR
    //beforeSend: function(xhr) { 
    //  xhr.setRequestHeader("X-Download, "yes"); 
    //}
}).done(function(data) { 
    alert(data);
});

For download take a look at Download a file by jQuery.Ajax