views:

1114

answers:

3

I am trying to download an Excel file using Ajax (XMLHttpRequest).

On completion the responseText is found to have just 5 characters.
The network sniffing tool (Fiddler) is showing me that my computer received the entire file..

so why is the responseText showing me only 5 characters? I have tried both Synch and Asynch calls.

Thanks for any help you can give here.

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);
A: 

Do not use Ajax call (xmlhttprequest) to download/upload files. Better do it on server side.

Krunal
A: 

Is your question the same as this one?

http://stackoverflow.com/questions/676348/allow-user-to-download-file-using-ajax

Ramiz Uddin
I am actually trying out the Iframe approach mentioned there. Was really hoping that somebody knows some other trick... which is just ajax.
rk2010
Ajax doesn't have such power. And I hope they'll keep this way. It gives us so much power and a single wrong assessment could make this thing very dangerous.
Ramiz Uddin
+1  A: 

The issue is probably that XMLHttpRequest doesn't ususally take binary data like an Excel file. If you just want to let the user download the file, read Ramiz's post. If you need to read the data in JavaScript, try switching to a text format like CSV (or better for parsing, JSON). If you really need to read a binary file, there are discussions of that here and here.

Annie
Thanks so much for providing those two links. I am using the VBscript solution which allows us to get a handle on the responseBody. and then read in the bytes out of it. Its working great.
rk2010