"How to check if image / file exist at given path?"
I have tried using .done,.fail,.success,.complete and many more tricks that I could use. Even I tried Try.. Catch .. finally. But the real issue was if file does not exist at URL it will give exception 404. But not throw it so it won't be cached. Finally I came across a method shown below which gives me 404 error but will return result.
Answer:
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send(); // Here it will generate 404
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
Calling :
if (doesFileExist(filePath)) {
// yay, file exists!
} else {
// oops, file not exist!
}
No comments:
Post a Comment