Data encoding is different in ajax success handler

元气小坏坏 提交于 2019-12-24 09:58:47

问题


I am using AJAX to download the excel file from server. But the downloaded data is different from actual data

Actual data is with orange background. Received data is in yellow background.

From the difference file, it looks like they are using different encoding formats. So excel throws error that the file is not in correct format.

    $.ajax({
        url: exporting.action,
        headers: { "Authorization": "Basic " + btoa("key : " + key) },
        type: "post",
        responseType: "arraybuffer",
        success: function (res, status, obj) {                
            var blob = new Blob([str2ab(res)], { type: obj.getResponseHeader('Content-Type') });                
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        },
        data: { 'Model': JSON.stringify(modelClone) }
    });

Please help to resolve this


回答1:


The trouble with "encoding" is caused that jQuery did not response arraybuffer but string. Strings are in JavaScript UTF-16 and binary data in string cause trouble next to trouble. I recommend you to use native AJAX instead of jQuery. Code is similar and browser support is the same as the browser support of blobs and object URLS what you use.

var xhr = new XMLHttpRequest();
xhr.open("POST", exporting.action);
xhr.setRequestHeader("Authorization", "Basic " + btoa("key : " + key));
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') });
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }
}.bind(this);
xhr.send({ 'Model': JSON.stringify(modelClone)});


来源:https://stackoverflow.com/questions/44132630/data-encoding-is-different-in-ajax-success-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!