从Ajax调用下载文件



我正在尝试使用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

最新更新