How do I check if file exists in jQuery or pure JavaScript?

前端 未结 18 2069
闹比i
闹比i 2020-11-22 00:56

How do I check if a file on my server exists in jQuery or pure JavaScript?

相关标签:
18条回答
  • 2020-11-22 01:14

    JavaScript function to check if a file exists:

    function doesFileExist(urlToFile)
    {
        var xhr = new XMLHttpRequest();
        xhr.open('HEAD', urlToFile, false);
        xhr.send();
    
        if (xhr.status == "404") {
            console.log("File doesn't exist");
            return false;
        } else {
            console.log("File exists");
            return true;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:17

    Here's my working Async Pure Javascript from 2020

    function testFileExists(src, successFunc, failFunc) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState === this.DONE) {
                if (xhr.status === 200) {
                    successFunc(xhr);
                } else {
                    failFunc(xhr);
                }
            }
        }
        // xhr.error = function() {
        //     failFunc(xhr);
        // }
        // xhr.onabort = function() {
        //     failFunc(xhr);
        // }
        // xhr.timeout = function() {
        //     failFunc(xhr);
        // }
        xhr.timeout = 5000;           // TIMEOUT SET TO PREFERENCE (5 SEC)
        xhr.open('HEAD', src, true);
        xhr.send(null);               // VERY IMPORTANT
    }
    function fileExists(xhr) {
        alert("File exists !!  Yay !!");
    }
    function fileNotFound(xhr) {
        alert("Cannot find the file, bummer");
    }
    testFileExists("test.html", fileExists, fileNotFound);
    

    I could not force it to come back with any of the abort, error, or timeout callbacks. Each one of these returned a main status code of 0, in the test above, so I removed them. You can experiment. I set the timeout to 5 seconds as the default seems to be very excessive. With the Async call, it doesn't seem to do anything without the send() command.

    0 讨论(0)
  • 2020-11-22 01:21

    First creates the function

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

    After using the function as follows

    if($.UrlExists("urlimg")){
    	foto = "img1.jpg";
    }else{
    	foto = "img2.jpg";
    }
    
    $('<img>').attr('src',foto);

    0 讨论(0)
  • 2020-11-22 01:23

    What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.

    What type of server are you trying to communicate with? You may need to write a small service to respond to the request.

    0 讨论(0)
  • 2020-11-22 01:26

    Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:

    async function isUrlFound(url) {
      try {
        const response = await fetch(url, {
          method: 'HEAD',
          cache: 'no-cache'
        });
    
        return response.status === 200;
    
      } catch(error) {
        // console.log(error);
        return false;
      }
    }
    

    Then inside your other async scope, you can easily check whether url exist:

    const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
    
    console.log(isValidUrl); // true || false
    
    0 讨论(0)
  • 2020-11-22 01:26

    An async call to see if a file exists is the better approach, because it doesn't degrade the user experience by waiting for a response from the server. If you make a call to .open with the third parameter set to false (as in many examples above, for example http.open('HEAD', url, false); ), this is a synchronous call, and you get a warning in the browser console.

    A better approach is:

    function fetchStatus( address ) {
      var client = new XMLHttpRequest();
      client.onload = function() {
        // in case of network errors this might not give reliable results
        returnStatus( this.status );
      }
      client.open( "HEAD", address, true );
      client.send();
    }
    
    function returnStatus( status ) {
      if ( status === 200 ) {
        console.log( 'file exists!' );
      }
      else {
        console.log( 'file does not exist! status: ' + status );
      }
    }
    

    source: https://xhr.spec.whatwg.org/

    0 讨论(0)
提交回复
热议问题