我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
这是我从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()命令,它似乎不会做任何事情。
其他回答
这并没有解决OP的问题,但对于任何从数据库返回结果的人来说:这里是我使用的一个简单方法。
如果用户没有上传头像,头像字段将为NULL,所以我将从img目录插入一个默认头像图像。
function getAvatar(avatar) {
if(avatar == null) {
return '/img/avatar.jpg';
} else {
return '/avi/' + avatar;
}
}
then
<img src="' + getAvatar(data.user.avatar) + '" alt="">
我使用这个脚本添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
http://wap.w3schools.com/jsref/event_onerror.asp
由于缓存,所有其他答案都可能失败!
向服务器上的文件发出HTTP请求可以被HTTP缓存拦截,然后返回缓存的响应。但是在此期间,该文件可能会在服务器上被删除,因此忽略缓存可能会返回假阳性结果。
合适的解决方案是创建非缓存的HTTP HEAD请求。Nik Sumeiko的回答使用了无缓存头,这意味着响应可以被缓存,但在重用之前必须重新验证。在这种情况下,服务器可能会返回304:Not Modified,而不是200:OK,因此是假阴性。
为了避免缓存,正确的头是cache - control: no-store
文件可以在没有HTTP 200响应的情况下存在
您还应该记住,可能会发生重定向(301:永久移动,307:临时重定向或308:永久重定向),因此文件可以存在于其他地方,并可能从不同的位置返回:根据用例,在这种情况下可以选择重定向而不是返回false。
另外请记住,如果您在不同的域上检查文件是否存在,并且它的CORS策略没有打开到您的服务器,后台请求将被阻止。在本例中,通常返回403:Forbidden,这并不意味着文件不存在,而是文件不可用。最后,同样适用于500:Internal Server Error响应,这意味着HTTP服务器未能处理请求,但该文件可以通过其他方式可用,例如通过FTP。
如果文件存在则返回true,如果不存在则返回false,如果文件不可用或重定向则返回undefined:
const fileExists = file =>
fetch(file, {method: 'HEAD', cache: 'no-store'})
.then(response => ({200: true, 404: false})[response.status])
.catch(exception => undefined);
fileExists("yourFile.html").then(yes => yes && alert("yourFile.html exists"));
// or in the async scope...
let yourFileExists = await fileExists("yourFile.html");
if(yourFileExists) console.log("It is there!")
else if(yourFileExists===false) console.log("Nope, it was deleted.");
else console.log("You are not worthy the answer, puny human!");
现代和过时的方法
既然我们现在生活在未来,我还会建议:
$.ajax()过时,不要在新项目中使用 XMLHttpRequest()过时,不要在新项目中使用 Fetch()现代方法,如果您可以自由选择,请使用它
注意GET/POST方法(如<img src…>)在这里不合适,因为它们通过下载文件浪费了网络流量(想象一下高分辨率照片和用户在连接较差的地区使用付费移动数据的最坏情况)
注意:现代PWA方法是使用缓存API和serviceWorker的fetch事件来拦截客户端和HTTP缓存之间的通信。在链接中的例子中,应该有这样的东西
if(event.request.cache=="no-store") {
// avoid cache storage and pass the request in the chain
// client - cache storage - HTTP cache - server
return fetch(event.request);
}
如果不这样做,缓存设置可能会被忽略,并且可能没有办法从运行serviceWorker的主线程中检测到远程文件的存在-如图所示 在这里。
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;
}
}
我想要一个函数,将返回布尔值,我遇到了闭包和异步性相关的问题。我是这样解决的:
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);
},