I'm sending xhr
request to server to download a file. I'm including authorization token into the request so I can't download a file without using xhr
. What steps should I take to make browser download a file when response from the server is received? And what headers should the server include?
Asked
Active
Viewed 1.1k times
6

Danny Fardy Jhonston Bermúdez
- 5,500
- 5
- 25
- 37

Max Koretskyi
- 101,079
- 60
- 333
- 488
-
2You can stuff the server response into a data URL, put it on an `` and trigger a click. Note that the `download` attribute is [not well supported](http://caniuse.com/#feat=download). Or, you can use a normal form submit (not XHR), sending your token in a hidden input instead of in a request header. – Amadan Sep 17 '15 at 06:26
-
@Amadan, thanks. These are the only options, right? – Max Koretskyi Sep 17 '15 at 10:39
-
I won't say that - but the only ones I can think of. – Amadan Sep 17 '15 at 10:41
-
It seems that [this one](http://stackoverflow.com/a/23797348/2545680) might do? – Max Koretskyi Sep 17 '15 at 10:49
-
1Yes, that's the code for "stuff the server response into a data URL, put it on an `` and trigger a click". – Amadan Sep 18 '15 at 09:33
1 Answers
8
This is a piece of code that works for me. Im using it for testing so its not the cleanest way I guess. But it can show a picture.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var downloadUrl = URL.createObjectURL(xhttp.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = downloadUrl;
a.download = "";
a.click();
}
};
xhttp.open("GET", fileUrl, true);
xhttp.responseType = "blob";
xhttp.setRequestHeader('Authorization', token);
xhttp.send();
This piece is not crucial, I was just need it in my case:
xhttp.setRequestHeader('Authorization', token);
This link can be usefull as well: Sending and Receiving Binary Data

tarasikarius
- 523
- 6
- 13