【问题标题】:Download a file from AJAX call从 AJAX 调用下载文件
【发布时间】:2019-07-31 07:33:57
【问题描述】:

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

}

【问题讨论】:

    标签: javascript java spring-mvc extjs


    【解决方案1】:

    您需要设置 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

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2014-05-27
      • 2011-11-26
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      相关资源
      最近更新 更多