javascript check if file exists on server

How to Check if a File Exists on the Server using Javascript?

If you are working on a web application that requires downloading files from the server, it is necessary to check whether the file exists on the server before attempting to download it. In this case, Javascript comes in handy to perform this task.

Method 1: Using XMLHttpRequest Object

The XMLHttpRequest object is used to make AJAX requests to the server. We can use this object to check whether a file exists on the server or not. The following code snippet demonstrates how to check if a file exists on the server using the XMLHttpRequest object:


function fileExists(url) {
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status != 404;
}

In this code snippet, we have defined a function named fileExists() that takes the URL of the file as an argument. The function creates an instance of the XMLHttpRequest object and sends a head request to the server using the http.open() method. The http.send() method sends the request to the server. If the file exists on the server, the status code returned by the server will be 200. If the file does not exist, the server will return a 404 status code. We check whether the status code is not equal to 404 to determine whether the file exists or not.

Method 2: Using jQuery

If you are using jQuery in your web application, you can use its $.ajax() method to check whether a file exists on the server. The following code snippet demonstrates how to use jQuery to check if a file exists on the server:


function fileExists(url) {
  var http = $.ajax({
    type:"HEAD",
    url: url,
    async: false
  });
  return http.status != 404;
}

Here, we have defined a function named fileExists() that takes the URL of the file as an argument. The function uses the $.ajax() method to send a head request to the server using the type:"HEAD" option. The async:false option makes the request synchronous. The status code returned by the server is checked to determine whether the file exists or not.

Conclusion

These were the two methods to check whether a file exists on the server using Javascript. You can use any of these methods depending on your requirements. However, it is recommended to use the XMLHttpRequest method as it is a native Javascript method and does not require any external library.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe