how to check if file exists on server in javascript code example
Example 1: javascript check if file exists on server
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
Example 2: javascript file exists check
// checking existence of file synchronously
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
return xhr.status !== 404;
}