[英]How to make browser download file from xhr request
我正在向服務器發送xhr
請求以下載文件。 我在請求中包含了授權令牌,因此如果不使用xhr
就無法下載文件。 收到服務器的響應后,應采取什么步驟使瀏覽器下載文件? 服務器應包含哪些標頭?
這是一段對我有用的代碼。 我正在使用它進行測試,所以我猜它不是最干凈的方法。 但是它可以顯示圖片。
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();
這部分並不重要,我只需要它:
xhttp.setRequestHeader('Authorization',令牌);
此鏈接也可能有用: 發送和接收二進制數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.