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

前端 未结 18 2084
闹比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: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/

提交回复
热议问题