繁体   English   中英

从AJAX调用下载文件

[英]Download a file from AJAX call

我正在尝试使用ExtJS从AJAX调用的响应中下载文件。 从服务器端,我使用Java和Spring发送文件的字节流。 我认为这很好用,因为当我使用Postman时,我可以毫无问题地下载文件。

当我尝试从浏览器(Chrome)下载该文件时,尽管下载有效,但该文件似乎已损坏。 首先,我选择所需的文件类型(CSV,PDF或Excel),后端将我的文件转换为该文件,然后将其发送到前端。 CSV可以使用,但PDF却不显示任何内容,Excel表示文件已损坏。 从我的尝试中,我认为问题可能出在编码上,发送的字节流与Chrome下载的字节流不同。

这是ExtJS代码:

function runScript(id, text) {
Ext.Ajax.request({
    url: 'http://localhost:8080/report/execute',
    useDefaultXhrHeader: false,
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    jsonData: { id: id,
                type: text },
    cors: true,
    waitMsg: 'Sending data ...',
    success: function (response) {
        var disposition = response.getResponseHeader('Content-Disposition');
        var filename = disposition.slice(disposition.indexOf("=")+1,disposition.length);
        var blob = new Blob([response.responseText]);
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob(blob, filename);
        }
        else {
            var URL = window.URL || window.webkitURL;
            var downloadUrl = URL.createObjectURL(blob);
            if (filename) {
                // use HTML5 a[download] attribute to specify filename
                var a = document.createElement("a");
                // safari doesn't support this yet
                a.href = downloadUrl;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
            }
        }
            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
    },
    failure: function () {
        Ext.Msg.alert('Failed', 'Download failed!');
    }
});

Ext.getCmp('sqlview').getStore().load();

}

您需要设置Blob中包含的数据的MIME类型。

var contentType = response.getResponseHeader('Content-Type');
var blob = new Blob([response.responseText], {
  type: contentType
});

确保您的后端为“ Content-Type”提供了正确的值。 文件类型的期望值为:

  • CSV: text/csv
  • PDF: application/pdf
  • Excel: application/vnd.ms-excel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM