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

前端 未结 18 2073
闹比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

    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);

提交回复
热议问题