Monday 6 July 2015

JavaScript check if file exist at URL or not.

I was trying simple things lately with client side object modal. Here is one of the main issue I have face

"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