Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript检查文件是否存在失败_Javascript - Fatal编程技术网

使用javascript检查文件是否存在失败

使用javascript检查文件是否存在失败,javascript,Javascript,我这里有一些答案,但不知怎么的,结果显示我错了。它全部输出文件存在即使它实际上并不存在 function doesFileExist(urlToFile) { var xhr = new XMLHttpRequest() xhr.open('HEAD', urlToFile, false) xhr.send() return console.log(xhr.status == 200 ? 'File exists' : 'File doe

我这里有一些答案,但不知怎么的,结果显示我错了。它全部输出
文件存在即使它实际上并不存在

    function doesFileExist(urlToFile) {
      var xhr = new XMLHttpRequest()
      xhr.open('HEAD', urlToFile, false)
      xhr.send()

      return console.log(xhr.status == 200 ? 'File exists' : 'File does not exist')
    }
它输出:

文件存在

这是服务器文件夹结构:


尝试检查是否大于400

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

doesFileExist('/Framework/views/login/activate_studeasdfnt.php')
服务器

if(isset($_POST['change_modal_content_activate'])){
    $url = dirname(__DIR__) . $init->post('url');
    var_dump(file_exists($url));
}

试试看。我已经测试过了。对不起,耽误了太长时间。另外,如果您的功能是测试文件是否存在,我建议检查200响应。但这取决于你。

这是同一个问题。遗憾的是,由于我的声誉,我无法发表评论。我尝试了所有的答案,那么xhr.status是什么,我们知道它不是404。通常情况下,状态为200表示请求已工作(但不一定是“文件存在”)一些浏览器不再发送同步请求,尽管将async argument设置为false。大于20o或不等于200,它们都输出相同的sir James,文件existsIt看起来您正试图使用客户端JS检查服务器端文件。那不行。相同的输出,先生,文件存在文件存在吗?如果我在我的控制台中运行它,它会正常工作。在else
console.log(“文件存在”+xhr.status)中添加它仍然,但状态是200我要发布我的文件夹结构安全提示1:不要传递完整的文件名,你透露了太多关于系统构建的信息。只需传递
user\u level
字符串,然后在服务器端生成文件名。安全提示2:不要信任传递给
user\u level
的值。如果有人传入一个值,比如
。/../../../../etc/foo
?与其用字符串构建文件名,不如检查它是否存在于硬编码数组中,或者构建一个类名并使用
class\u exists()
。嘿@Fear,修复了你原来的帖子。你是什么意思,先生@noyancheck我的答案。我已经用您提供的代码修复了您的问题您好,先生!对不起,我以前没有感谢过你,这是因为我名声不好。但现在,我要表达我的感激之情,我成功地走出了那个洞。非常感谢。
if(isset($_POST['change_modal_content_activate'])){
    $url = dirname(__DIR__) . $init->post('url');
    var_dump(file_exists($url));
}
function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();
    if (xhr.readyState == 4 && xhr.status == 404 ) {
        console.log("File doesn't exist");
        return false;
    } else {
        console.log("File exists");
        return true;
    }
}

doesFileExist('/Framework/views/login/activate_studeasdfnt.php')