Hi everyone! How to use javascript to determine whether a file exists in a directory?
A:
I don't know if there's an elegant way to do this, but for a lightweight solution you could try and load the file as the src to an Image object, and handle the onerror event.
Tom Ritter
2009-08-11 03:06:42
+5
A:
If the JavaScript is running in a web browser, you do not have access to the local filesystem. If there were a way to get access to the local filesystem, it would be considered a security hole that would be fixed by the browser vendor.
Nate
2009-08-11 03:07:55
does a firefox extension count as "in a web browser" ? You can access the filesystem from there.
Breton
2009-08-11 08:47:42
An extension is not running *in* a web browser, it is running *as part of* a web browser.
NickFitz
2009-08-11 13:22:26
+4
A:
If it's on the server, you could make an HTTP HEAD request via Ajax, and look if the HTTP Status Code is 404 (Not found) or 200 (Ok).
An example using jQuery:
$.ajax({
type: 'HEAD',
url: 'somefile.ext',
complete: function (xhr){
if (xhr.status == 404){
alert(xhr.statusText); // Not found
}
}
});
CMS
2009-08-11 04:01:31