【问题标题】:ajax request to download an excel file is showing me truncated response下载 excel 文件的 ajax 请求显示我被截断的响应
【发布时间】:2010-12-28 23:47:17
【问题描述】:

我正在尝试使用 Ajax (XMLHttpRequest) 下载 Excel 文件。

完成后,responseText 仅包含 5 个字符。
网络嗅探工具 (Fiddler) 显示我的计算机收到了整个文件..

那么为什么 responseText 只显示 5 个字符?我已经尝试过同步和异步调用。

感谢您在此处提供的任何帮助。

var xmlHttpReq = getXmlHttpRequestObject();

function  getXmlHttpRequestObject(){
    var xmlhttp;

    if (window.XMLHttpRequest){// code for all new browsers
          xmlhttp=new XMLHttpRequest();

    }else if (window.ActiveXObject){// code for IE5 and IE6
         // xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

        progids = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'Microsoft.XMLHTTP'];

        for (i=0 ; i < progids.length; i ++){
            try {
                xmlhttp = new window.ActiveXObject(progids[i]);
                break;
            } catch (e) {
              //do nothing
            }
        }


    }


    return xmlhttp;


}

//utility method for http get
function doSynchronousGet(url){
    if(xmlHttpReq == null){
        xmlHttpReq = getXmlHttpRequestObject();
    }

    //change last param to true for making async calls.
    xmlHttpReq.open("GET" ,url,false);
    xmlHttpReq.setRequestHeader("Connection", "close");
    xmlHttpReq.send(null);
    return xmlHttpReq.responseText;
}



var resultText = doSynchronousGet(url);

alert('resultText length: '+ resultText.length);
alert('resultText: '+ resultText);

【问题讨论】:

    标签: ajax xmlhttprequest download


    【解决方案1】:

    问题可能是 XMLHttpRequest 通常不会像 Excel 文件那样获取二进制数据。如果您只想让用户下载文件,请阅读 Ramiz 的帖子。如果您需要在 JavaScript 中读取数据,请尝试切换到 CSV 之类的文本格式(或者更适合解析的 JSON)。如果你真的需要读取二进制文件,可以讨论herehere

    【讨论】:

    • 非常感谢您提供这两个链接。我正在使用允许我们处理 responseBody 的 VBscript 解决方案。然后读入其中的字节。它工作得很好。
    • Ramiz 的帖子在哪里?
    【解决方案2】:

    不要使用 Ajax 调用 (xmlhttprequest) 来下载/上传文件。最好在服务器端做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-07
      • 2018-03-20
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多