Javascript 使用blob从ajax结果下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29393601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:17:37  来源:igfitidea点击:

Downloading file from ajax result using blob

javascriptjquery

提问by SMGhost

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. 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.

我遇到的问题是,即使数据和 blob 大小相同,但在分配 document.location 的那一刻,我会被提示下载几乎两倍大的 excel 文件。当我尝试打开它时,excel 抱怨文件格式错误并且打开的文件包含大量垃圾,即使所需的文本仍然存在。

Any ideas what is causing this and how to avoid it?

任何想法是什么导致了这种情况以及如何避免它?

回答by SMGhost

So I solved the problem using AJAX 2. It natively supports binary streams. You can't use jQuery for that, unless you base64 encode everything, apparently.

所以我使用 AJAX 2 解决了这个问题。它本身支持二进制流。显然,除非您对所有内容进行 base64 编码,否则您不能为此使用 jQuery。

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.

希望这可以帮助。