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


当前回答

这对我来说很管用:

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

其他回答

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

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

如果你使用Babel transpiler或Typescript 2,下面是如何用ES7的方式来做:

async function isUrlFound(url) {
  try {
    const response = await fetch(url, {
      method: 'HEAD',
      cache: 'no-cache'
    });

    return response.status === 200;

  } catch(error) {
    // console.log(error);
    return false;
  }
}

然后在你的其他异步作用域中,你可以很容易地检查url是否存在:

const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');

console.log(isValidUrl); // true || false

这是我从2020年开始工作的Async纯Javascript

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

我不能强迫它返回任何中止、错误或超时回调。 在上面的测试中,每一个都返回一个主状态代码0,所以 我把它们拿掉了。你可以尝试。 我将超时时间设置为5秒,因为默认值似乎太大了。 对于Async调用,如果没有send()命令,它似乎不会做任何事情。

当我试图运行这个问题的答案时,我遇到了一个跨域权限问题,所以我去了:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;
});
}

它似乎工作得很好,希望这有助于某人!

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

我们需要验证一个本地文件是否存在,并且只允许该文件(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");

    }
});