...

View Full Version : Checking File is exists or not by using JavaScript?



santoshsrinivas
03-27-2012, 12:09 PM
Hai Forum,

May be this question is not in correct format,
I want to know about how to check a particular file is exists or not ? using Javascript.One thing without using ActiveXObject because it is supports in IE only.

Thanking You,
Santosh Srinivas.G

Mishu
03-27-2012, 12:18 PM
If the file is on the server then you can use AJAX. If it's on the user's local machine then I don't think you can do it other than how you said you don't want to use.

DaveyErwin
03-27-2012, 12:19 PM
function exists?(strURL){
req = new XMLHttpRequest;
req.open("HEAD", strURL, false);
req.send();
return (req.status==404) ? false : true;
}

Old Pedant
03-27-2012, 10:39 PM
Note that Davey's answer only works if the file is on the same server that the web page came from. And even then only if the file is accessible via HTTP (that is, not in some directory that the web server is disallowed access to). But yes, it's by far the easiest way to do this.

rnd me
03-27-2012, 11:49 PM
one minor point of clarification:

javascript can see files from the same origin as the page the user is looking at. If you are serving the html page from a local file, then you indeed CAN check for files locally. If your html runs on an http server, you can only use ajax to look for file on that server.


in the case of local files, a code like the one posted will work.
IE doesn'y do status correctly, and there's also no 404s to contend with:



function exists(strURL){
var req = new XMLHttpRequest;
req.open("GET", strURL, false);
req.send();
return !! req.responseText;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum