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

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

    JavaScript function to check if a file exists:

    function doesFileExist(urlToFile)
    {
        var xhr = new XMLHttpRequest();
        xhr.open('HEAD', urlToFile, false);
        xhr.send();
    
        if (xhr.status == "404") {
            console.log("File doesn't exist");
            return false;
        } else {
            console.log("File exists");
            return true;
        }
    }
    

提交回复
热议问题