Thursday, June 26, 2008

Use xmlHTTPRequest for Accessing Local Files

here are some of my experiences working with xmlHTTPRequest object to open local files.
xhr.open("GET",localFile,false);          
httpRequest.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//blahblah...
} else {
//blahblah...
}
}
xhr.send(null);


First of all, there will be exceptions if you trying to access a local file that doesn't exist. Instead of returning 404 status code, it throws out an exception. In addition, the status code from opening local files will be 0. Below is quote from Mozilla website for xmlHTTPRequest object.

file:/// and ftp:// do not return HTTP status, which is why they return zero for status and an empty string for statusText. please refer to bug 331610 for more insight.

I didn't find any IE related document to xmlHTTPRequest object, but from my test, it also return 0 for file:///.

Below is the modification to original code
try {
xhr.open("GET",localFile,false);
httpRequest.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status < 300) {
//blahblah...
} else {
//blahblah...
}
}
}
xhr.send(null);
} catch (ex) {
//blahblah...
}

No comments: