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

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

    With jQuery:

    $.ajax({
        url:'http://www.example.com/somefile.ext',
        type:'HEAD',
        error: function()
        {
            //file not exists
        },
        success: function()
        {
            //file exists
        }
    });
    

    EDIT:

    Here is the code for checking 404 status, without using jQuery

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

    Small changes and it could check for status HTTP status code 200 (success), instead.

    EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:

    function executeIfFileExist(src, callback) {
        var xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function() {
            if (this.readyState === this.DONE) {
                callback()
            }
        }
        xhr.open('HEAD', src)
    }
    
    0 讨论(0)
  • 2020-11-22 01:30

    So long as you're testing files on the same domain this should work:

    function fileExists(url) {
        if(url){
            var req = new XMLHttpRequest();
            req.open('GET', url, false);
            req.send();
            return req.status==200;
        } else {
            return false;
        }
    }
    

    Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file. If the file is big enough this method can take a while to complete.

    The better way to do this would be changing this line: req.open('GET', url, false); to req.open('HEAD', url, false);

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

    For a client computer this can be achieved by:

    try
    {
      var myObject, f;
      myObject = new ActiveXObject("Scripting.FileSystemObject");
      f =   myObject.GetFile("C:\\img.txt");
      f.Move("E:\\jarvis\\Images\\");
    }
    catch(err)
    {
      alert("file does not exist")
    }
    

    This is my program to transfer a file to a specific location and shows alert if it does not exist

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

    This works for me:

    function ImageExist(url) 
    {
       var img = new Image();
       img.src = url;
       return img.height != 0;
    }
    
    0 讨论(0)
  • 2020-11-22 01:34

    I use this script to check if a file exists (also it handles the cross origin issue):

    $.ajax(url, {
           method: 'GET',
           dataType: 'jsonp'
             })
       .done(function(response) { 
            // exists code 
        }).fail(function(response) { 
            // doesnt exist
        })
    

    Note that the following syntax error is thrown when the file being checked doesn't contain JSON.

    Uncaught SyntaxError: Unexpected token <

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

    A similar and more up-to-date approach.

    $.get(url)
        .done(function() { 
            // exists code 
        }).fail(function() { 
            // not exists code
        })
    
    0 讨论(0)
提交回复
热议问题