下载 Spring Rest 文件带 Header 的两种方法

下载文件通常是一个 Link 就可以搞定的, Spring Rest 下载有什么特别的,这里的问题是 Spring Rest 常常是无状态的,所以可能在下载时需要传递 Header, 这是 a 标签无法给出的,因此这里给出两种 js 代码加 Header 下载的方式,其实是一种方式,xhr 和用 jQuery 包装过的 xhr, 下面代码以供参考:

  • xhr

var downloadUrl = apiUrl + "fileInfo/" + this.getAttribute("id");
var fileName = this.getAttribute("value")

var xhr = new XMLHttpRequest();
xhr.open('get', downloadUrl, true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Authorization", token);
xhr.onload = function(e) {
    if (this.status == 200) {
        var blob = new Blob([this.response], {type: 'application/octet-stream'});
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    } else {
        alert('文件下载失败!')
    }
};
xhr.send();
  • jQuery

 $.ajax({
     type: 'get',
     url: " http://10.10.190.222:9080/QualityCheck/dev/excel/statisExport/2",
     headers: {
         'Authorization': token
     },
     // xhrFields: {
     //     responseType: 'blob'
     // },
     // 当出错时是text,因此不能直接设blob
     xhr: function () {
         var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 2) {
                 if (xhr.status == 200) {
                     xhr.responseType = "blob";
                 } else {
                     xhr.responseType = "text";
                 }
             }
         };
         return xhr;
     },
     success: function (response, msg, xhr) {
         var blob = new Blob([response], { type: 'application/octet-stream' });
         var filename = "成果汇总表.xlsx";
         var download_URL = URL.createObjectURL(response);
         if (filename) {
             var a_link = document.createElement('a');
             a_link.rel = 'noopener';
             if (typeof a_link.download == 'undefined') {
                 window.location = download_URL;
             } else {
                 a_link.href = download_URL;
                 a_link.download = filename;
                 document.body.appendChild(a_link);
                 a_link.click();
             }
         } else {
             window.location = download_URL;
         }
         setTimeout(function () {
             URL.revokeObjectURL(download_URL);
         }, 10000);

     },
     error: function (error) {
         console.log("error ", error)
     }
 });

你可能感兴趣的:(技术归档)