3

How to use javascript to determine whether a file exists in a directory?

bluish
  • 26,356
  • 27
  • 122
  • 180
lanqy
  • 3,001
  • 5
  • 25
  • 18

4 Answers4

11

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
    }
  }
});
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
6

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
  • 18,752
  • 8
  • 48
  • 54
0

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
  • 99,986
  • 30
  • 138
  • 174
0
var fso = new ActiveXObject("Scripting.FileSystemObject");
var folderPath="set you path here";
//to check whether folder exists
fso.FolderExists(folderPath)) 
//to check whether file exists          
alert(fso.FileExists(folderPath+ "\\<filename>"));

How to use JavaScript to determine whether a directory exists?

Community
  • 1
  • 1
EMM
  • 1,812
  • 8
  • 36
  • 58