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

前端 未结 18 2077
闹比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)
    }
    

提交回复
热议问题