我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?


当前回答

这对我来说很管用:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

其他回答

JavaScript函数检查文件是否存在:

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

这是对公认答案的改编,但我不能从答案中得到我需要的东西,必须测试它是否有效,因为这是一种直觉,所以我把我的解放在这里。

我们需要验证一个本地文件是否存在,并且只允许该文件(PDF)在存在的情况下打开。如果你省略了网站的URL,浏览器将自动确定主机名-使其在localhost和服务器上工作:

$.ajax({

    url: 'YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf',
    type: 'HEAD',
    error: function () {
        //file not exists
        alert('PDF does not exist');

    },
    success: function () {
        //file exists
        window.open('YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf', "_blank", "fullscreen=yes");

    }
});

我使用这个脚本来检查一个文件是否存在(它也处理交叉起源问题):

$.ajax(url, {
       method: 'GET',
       dataType: 'jsonp'
         })
   .done(function(response) { 
        // exists code 
    }).fail(function(response) { 
        // doesnt exist
    })

请注意,当检查的文件不包含JSON时,会抛出以下语法错误。

未捕获SyntaxError:意外的令牌<

一种类似的和最新的方法。

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

我想要一个函数,将返回布尔值,我遇到了闭包和异步性相关的问题。我是这样解决的:

checkFileExistence= function (file){
    result=false;
    jQuery.ajaxSetup({async:false});
    $.get(file)
        .done(function() {
           result=true;
        })
        .fail(function() {
           result=false;
        })
    jQuery.ajaxSetup({async:true});
    return(result);
},