Get excel file (.xlsx) from server response in ajax

后端 未结 2 1728
旧巷少年郎
旧巷少年郎 2020-12-16 21:45

I have got a problem with getting excel file and opening download window in the browser after getting a response (in success ajax method) with that file. I have got appropri

相关标签:
2条回答
  • 2020-12-16 21:59

    We were having absolutely the same trouble recently. For us it started to work when we add responseType: 'arraybuffer' to the ajax parameters. And it's better to use lib https://github.com/eligrey/FileSaver.js/ instead of manual clicking on the link because this tool revokes memory as well.

    0 讨论(0)
  • 2020-12-16 22:09

    It looks like JQuery have got some problem with dealing with the binary data from the response. I used simply XMLHttpRequest and I add all data to the URL.

    var request = new XMLHttpRequest();
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.responseType = 'blob';
    
    request.onload = function(e) {
        if (this.status === 200) {
            var blob = this.response;
            if(window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveBlob(blob, fileName);
            }
            else{
                var downloadLink = window.document.createElement('a');
                var contentTypeHeader = request.getResponseHeader("Content-Type");
                downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader }));
                downloadLink.download = fileName;
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
               }
           }
       };
       request.send();
    
    0 讨论(0)
提交回复
热议问题