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

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

提交回复
热议问题