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


当前回答

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

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

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

其他回答

只要你在同一个域上测试文件,这应该是有效的:

function fileExists(url) {
    if(url){
        var req = new XMLHttpRequest();
        req.open('GET', url, false);
        req.send();
        return req.status==200;
    } else {
        return false;
    }
}

请注意,这个例子使用了一个GET请求,它除了获取头信息(检查文件是否存在所需要的全部信息)之外,还会获取整个文件。 如果文件足够大,这个方法可能需要一段时间才能完成。

更好的方法是更改这一行:req。open('GET', url, false);要求的事情。open('HEAD', url, false);

您需要做的是向服务器发送一个请求,让它进行检查,然后将结果发回给您。

您试图与哪种类型的服务器通信?您可能需要编写一个小型服务来响应请求。

如果你使用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

首先创建函数

美元。UrlExists =函数(url) { var http = new XMLHttpRequest(); http。open('HEAD', url, false); http.send (); 还http.status ! = 404; }

使用函数后,如下所示

如果($.UrlExists(“urlimg”)){ 照片 = “IMG1.jpg”; }else{ 照片 = “IMG2.jpg”; } $(''<img>).attr('src',photo);

这是我从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()命令,它似乎不会做任何事情。