简体   繁体   English

使用blob从ajax结果下载文件

[英]Downloading file from ajax result using blob

I use this code to download excel file from server. 我使用此代码从服务器下载excel文件。

$.ajax({
    headers: CLIENT.authorize(),
    url: '/server/url',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(jsonData),
    success: function (data) {
        alert('Data size: ' + data.length);
        var blob = new Blob([data], { type: "application/vnd.ms-excel" });
        alert('BLOB SIZE: ' + data.length);
        var URL = window.URL || window.webkitURL;
        var downloadUrl = URL.createObjectURL(blob);
        document.location = downloadUrl;
    },
});

The problem I experience is that even though data and blob sizes are identical, the moment document.location gets assigned I'm prompted to download almoste two times larger excel file. 我遇到的问题是,尽管数据和blob大小相同,但是时刻document.location被分配我被提示下载almoste两倍大的excel文件。 And when I try to open it, excel complains about wrong file format and opened file contains a lot of garbage, even though required text is still there. 当我尝试打开它时,excel会抱怨错误的文件格式,并且打开的文件包含大量垃圾,即使必需的文本仍然存在。

Any ideas what is causing this and how to avoid it? 是什么导致了这个以及如何避免它?

So I solved the problem using AJAX 2. It natively supports binary streams. 所以我使用AJAX 2解决了这个问题。它原生支持二进制流。 You can't use jQuery for that, unless you base64 encode everything, apparently. 你不能使用jQuery,除非你对base64进行编码,显然。

Working code looks like this: 工作代码如下所示:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/le/url', true);
xhr.responseType = 'blob';
$.each(SERVER.authorization(), function(k, v) {
    xhr.setRequestHeader(k, v);
});
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function(e) {
    preloader.modal('hide');
    if (this.status == 200) {
        var blob = new Blob([this.response], {type: 'application/vnd.ms-excel'});
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "data.xls";
        document.body.appendChild(a);
        a.click();
    } else {
        alert('Unable to download excel.')
    }
};
xhr.send(JSON.stringify(jsonData));

Hope this helps. 希望这可以帮助。

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

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