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?
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?
-
2
You can stuff the server response into a data URL, put it on an
<a download>
and trigger a click. Note that thedownload
attribute is not well supported. Or, you can use a normal form submit (not XHR), sending your token in a hidden input instead of in a request header. – Amadan Commented Sep 17, 2015 at 6:26 - @Amadan, thanks. These are the only options, right? – Max Koretskyi Commented Sep 17, 2015 at 10:39
- I won't say that - but the only ones I can think of. – Amadan Commented Sep 17, 2015 at 10:41
- It seems that this one might do? – Max Koretskyi Commented Sep 17, 2015 at 10:49
-
1
Yes, that's the code for "stuff the server response into a data URL, put it on an
<a download>
and trigger a click". – Amadan Commented Sep 18, 2015 at 9:33
1 Answer
Reset to default 8This 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743782117a4505994.html
评论列表(0条)