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!
}

2 comments:

  1. Checking whether a file or image exists at a URL is a useful JavaScript task, especially when working with dynamically generated paths on the client side. The distinction between receiving a 404 response and actually throwing a JavaScript exception is important here, and using an XMLHttpRequest with a HEAD request is a straightforward way to handle that check.

    I like the approach of using doesFileExist() to keep the logic reusable rather than repeating the XMLHttpRequest code wherever a file needs to be checked. The xhr.status check also makes the intended behavior very clear, and this is a practical example for anyone working with JavaScript and remote resources. Javascript Online Training can be helpful for building a stronger understanding of XMLHttpRequest, HTTP responses, and similar client-side techniques.

    ReplyDelete
  2. It is also interesting that the initial attempts with .done(), .fail(), .success(), and exception handling did not address the actual behavior of the 404 response. Understanding how the browser handles HTTP status codes versus JavaScript exceptions can prevent a lot of confusion when troubleshooting these cases. Examples like this make Javascript Online Course material more practical because they connect basic JavaScript syntax with real browser behavior.

    ReplyDelete

The "Mark as Decorative" Feature in SharePoint: A Small Toggle With a Big Accessibility Impact

If you've spent any time building pages in SharePoint Online, you've probably noticed a new checkbox tucked inside the Accessibility...