6

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?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

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