How do I check if a file on my server exists in jQuery or pure JavaScript?
So long as you're testing files on the same domain this should work:
function fileExists(url) {
if(url){
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
return req.status==200;
} else {
return false;
}
}
Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file. If the file is big enough this method can take a while to complete.
The better way to do this would be changing this line: req.open('GET', url, false);
to req.open('HEAD', url, false);