我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
编辑:
下面是检查404状态的代码,不使用jQuery
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
小的改变,它可以检查状态HTTP状态码200(成功)。
编辑2:由于sync XMLHttpRequest已弃用,你可以添加一个这样的实用方法来异步执行:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
其他回答
这对我来说很管用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
编辑:
下面是检查404状态的代码,不使用jQuery
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
小的改变,它可以检查状态HTTP状态码200(成功)。
编辑2:由于sync XMLHttpRequest已弃用,你可以添加一个这样的实用方法来异步执行:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
由于缓存,所有其他答案都可能失败!
向服务器上的文件发出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的主线程中检测到远程文件的存在-如图所示 在这里。
您需要做的是向服务器发送一个请求,让它进行检查,然后将结果发回给您。
您试图与哪种类型的服务器通信?您可能需要编写一个小型服务来响应请求。
它为我工作,使用iframe忽略浏览器显示GET错误消息
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}