Dave's Brain

Browse - Programming Tips - How can I find out of a file exists using javaScript?

Date: 2009jun23
Language: javaScript
Platform: web

Q.  How can I find out of a file exists using javaScript?

A.  Do Ajax with the HEAD command like this:

// Helper function getAjax() { return (!window.XMLHttpRequest)? (new ActiveXObject('Microsoft.XMLHTTP')):(new XMLHttpRequest()); } function isExists(url) { var req; req = getAjax(); try { req.open('HEAD', url, false); // We block (ie wait for the return) req.send(null); } catch(e) { return false; // for IE6 } return req.status == 200; } function exampleUse() { var i; for (i = 1; i < 10000; i++) { padded = zeroPad(i, 5); if (!isExists('http://www.example.com/photos/DSC'+padded+'.JPG')) break; } var n = i - 1; alert('There are ' + n + ' photos'); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.