How to Check Mentioned File Exists or not using JavaScript/jQuery?


Using JavaScript or jQuery, we can check whether a file exists and retrieve metadata about the file, such as its size, content type, last modified date, etc., without retrieving the actual file. The HTTP HEAD request is used in this case. An HTTP HEAD request is a type of HTTP request that asks the server to return the HTTP headers for a specified resource without the actual resource itself.

Several methods can be used to send an HTTP HEAD request, but the most popular way is to use the $.ajax() method and XMLHttpRequest object. Users can define the request type as "HEAD" using either of these methods and can also include a callback function to deal with the response. The callback function will be invoked if the file exists with the server response. If the file does not exist, the callback function is not invoked, and an exception is thrown.

If we find the mentioned file exists, we can take any action after that, such as showing the actual file or displaying a message consisting of the file's metadata, etc. We can show an error message if the mentioned file doesn't exist. It will improve the performance that we did not try to get the actual large file; instead of we check its status.

Using ajax() method

To check if a file exists using the $.ajax() method in jQuery, we can use the following steps −

  • Create an object containing the type, 'url', 'success', and 'error' options. The type option should be set to "HEAD", the 'url' option should be set to the URL of the file we want to check, and the 'success' and 'error' options should be callback functions to handle the response if the request is successful or fails, respectively.

  • Call the '$.ajax()' method and pass in the object we created in step 1 as an argument.

  • Inside the 'success' callback function, we can take any desired action if the file exists. For example, we could display the file to the user or perform another operation.

  • Inside the 'error' callback function, we can take any desired action if the file does not exist. For example, we could display an error message or redirect the user to a different page

Syntax

$.ajax({ 
   url: url,
   type: 'HEAD',
   success: function () {
      // The mentioned file exist!
   },
   error: function () {
      // The mentioned file does not exist!
   },
})

The syntax shows that the type property is set to HEAD to specify that we are sending a HEAD request to the server. The url property is set to the URL of the server-side script or application to that we want to send the request.

Example

In this example, we check whether the mentioned file exists using the ajax method. We have used the ajax library of jQuery. An input field is put into different file paths to check whether they exist. If the file exists, the success function shows the ‘The mentioned file exist!’ message, and if the file does not exist, then the error function shows ‘The mentioned file does not exist!’ on the web page.

<html>
<head>
   <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
   <h2>Checking if Mentioned <i>File Exists or not</i> using JavaScript/jQuery</h2>
   <h4>Enter file path:</h4>
   <input id = "file_path" name = "file_path" />
   <button onclick="checkFile()">Check File</button>
   <div id = "root" style = "padding: 10px; background: #b8f0ea"></div> 
   <script>
      let root = document.getElementById('root')
      let file_path = document.getElementById('file_path')
      function checkFile() {
         $.ajax({
            url: file_path.value,
            type: 'HEAD',
            success: function () {
               root.innerHTML = 'The mentioned file exist!'
            },
            error: function () {
               root.innerHTML = 'The mentioned file does not exist!'
            },
         })
      }
   </script>
</body>
</html> 

Using XMLHttpRequest() method

To check if a file exists using the 'XMLHttpRequest' object in JavaScript, we can use the following steps −

  • Create a new 'XMLHttpRequest' object.

  • Use the 'open()' method of the 'XMLHttpRequest' object to specify the URL of the file we want to check, and set the request method to "HEAD".

  • Use the 'send()' method of the 'XMLHttpRequest' object to send the request.

  • Check the 'status' property of the 'XMLHttpRequest' object to see if the file exists. If the 'status' property is 200, the file exists; if the 'status' property is 404, the file does not exist.

Syntax

var http = new XMLHttpRequest()
http.open('HEAD', url, false)
http.send()
if (http.status === 200) {
   
   //This file exist!
} else {
   
   //This file does not exist!
} 

In the above syntax, we are using the XMLHttpRequest(), and based on the status code, we can write the code if the file exists or does not exist.

Example

In this example, we check whether the mentioned file exists using the XMLHttpRequest() method. An input field is put into different file paths to check whether they exist. If the file exists, then the status code will be 200, and we will show the ‘This file exists!’ message, and if the file does not exist, then the error function shows ‘This file does not exist!’ on the web page.

<html>
<body>
   <h2>Checking If Mentioned File Exists or not using JavaScript/ jQuery</h2>
   <h4>Enter file path:</h4>
   <input id = "file_path" name = "file_path" />
   <button onclick = "checkFile()">Check File</button>
   <div id = "root" style = "padding: 10px; background: #f0ecb8"></div>
   <script>
      let root = document.getElementById('root')
      let file_path = document.getElementById('file_path')
      function checkFile() {
         var http = new XMLHttpRequest()
         http.open('HEAD', file_path.value, false)
         http.send()
         if (http.status === 200) {
            root.innerHTML = 'This file exist!'
         } else {
            root.innerHTML = 'This file does not exist!'
         }
      }
   </script>
</body>
</html>

Checking whether the mentioned file exists is a good practice for using large data files, and JavaScript and jQuery give us the power to check it.

Updated on: 08-Feb-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements