1. 程式人生 > >js動態請求後臺下載檔案

js動態請求後臺下載檔案

<button type="button" onclick="download()">匯出</button>
function download() {
  var url = 'download/?filename=aaa.txt';
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);        // 也可以使用POST方式,根據介面
  xhr.responseType = "blob";    // 返回型別blob
  // 定義請求完成的處理函式,請求前也可以增加載入框/禁用下載按鈕邏輯
  xhr.onload = function () {
    // 請求完成
    if (this.status === 200) {
      // 返回200
      var blob = this.response;
      var reader = new FileReader();
      reader.readAsDataURL(blob);    // 轉換為base64,可以直接放入a標籤href
      reader.onload = function (e) {
        // 轉換完成,建立一個a標籤用於下載
        var a = document.createElement('a');
        a.download = 'data.xlsx';
        a.href = e.target.result;
        $("body").append(a);    // 修復firefox中無法觸發click
        a.click();
        $(a).remove();
      }
    }
  };
  // 傳送ajax請求
  xhr.send()
}