使用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:由于同步XMLHttpRequest已被弃用,因此您可以添加一个类似于这样的实用程序方法来进行异步操作:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
一种类似且更为时新的方法。
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
$.ajax
似乎更好,对吗? - tim peterson这对我有用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
我使用了这个脚本来添加替代图片
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
只要您在同一域上测试文件,这应该可以正常工作:
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);
改为req.open('HEAD', url, false);
。async: false
,在Firefox 30.0及更高版本以及最近/当前版本的Chrome中同步操作已被弃用,因为用户体验不佳。尝试使用会导致失败/错误。应该使用带有回调函数的async: true
进行异步操作。 - Kevin Fegan如果您使用 Babel 转译器或 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;
}
}
然后在您的其他async
作用域内,您可以轻松地检查url是否存在:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
当我尝试运行这个问题的答案时,出现了跨域权限问题,因此我选择了:
function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
return true;
}).bind('error', function() {
return false;
});
}
看起来运行良好,希望能对某些人有所帮助!
向服务器发出HTTP请求以获取文件时,可以通过HTTP缓存截取并返回缓存的响应。但是,文件可能会在此期间从服务器中删除,因此忽略缓存可能会返回错误的结果。
正确的解决方案是创建不被缓存的HTTP HEAD请求,Nik Sumeiko的答案使用了no-cache
头部,这意味着响应可以被缓存,但必须在重用之前重新验证。在这种情况下,服务器可能会返回304:未修改
,这不是200:OK
,因此会出现假阴性。
为了避免缓存,正确的标头是Cache-Control:no-store
你还应该记住,重定向(301:永久重定向
,307:临时重定向
或308:永久重定向
)可能会发生,因此文件可能存在于其他位置并可能从不同位置返回:根据用例,可以选择跟随重定向而不是在这种情况下返回false。
还要记住,如果你在不同的域中检查文件是否存在并且其CORS策略没有向你的服务器开放,则会阻止后台请求。在这种情况下,通常会返回403:禁止
,这并不意味着文件不存在,而是文件不可用。最后但并非最不重要的,对于500:内部服务器错误
响应也是适用的,这意味着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!");
既然我们现在生活在未来,我也建议:
注意 GET/POST方法(例如<img src...>
)不适用于此处,因为它们通过下载文件浪费网络流量(想象一下最坏的情况:高分辨率照片和在网络连接质量差的地区使用付费移动数据的用户)
注意 现代PWA方法是使用Cache 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中的远程文件是否存在 - 在此处说明here。
我使用这个脚本来检查文件是否存在(同时它还处理了跨域问题):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
Uncaught SyntaxError: Unexpected token <
用于检查文件是否存在的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;
}
}
return xhr.status == 200;
,将其转换为返回布尔结果的函数,并将服务器错误视为指向无法访问的文件。 - Jonas
OnReadyStateChange
事件。 - RobertPitt