我如何检查给定的网址是否有效图像,如果无效则为404(404),然后在20秒后重新检查并使用Javasript尝试这样5分钟
checkFileExists = function(){
$.ajax({
type: 'HEAD',
url: fileUrl,
crossDomain: true,
success: function(response) {
// Further processing if file exists
fileExists = true;
console.log(response);
},
error: function(error) {
// File does not exists, run through function again-
console.log(error);
fileExists = false;
}
});
}
if(!fileExists) {
setTimeout(function(){
checkFileExists();
}, 20000);
}
但是它不起作用会抛出错误'XMLHttpRequest无法加载XXXX否请求的资源上存在'Access-Control-Allow-Origin'标题。'
**我的文件网址是'https://drive.google.com/thumbnail?xxxx'我从我的localhost请求
答案 0 :(得分:1)
尝试在函数checkFileExists
中创建新的img元素,设置url图像并设置onError
事件函数。
var checkImage = function(url){
console.log("1");
var s = document.createElement("IMG");
s.src = url
s.onerror = function(){
console.log("file with "+url+" invalid");
alert("file with "+url+" invalid")
}
s.onload = function(){
console.log("file with "+url+" valid");
alert("file with "+url+" valid")
}
}
checkImage("http://ya.ru/favic2on.ico")

答案 1 :(得分:0)
我找到了两种有趣的方法来检查网络上的图片网址是否损坏:
function isImageOk(img) {
// During the onload event, IE correctly identifies any images that
// weren't downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
// No other way of checking: assume it's ok.
return true;
}
当页面加载时,我们遍历images []数组以检查它们。
addEvent(window, "load", function() {
for (var i = 0; i < document.images.length; i++) {
if (!isImageOk(document.images[i])) {
document.images[i].style.visibility = "hidden";
}
}
});
为了在20秒间隔内检查URL,您可以在循环中使用javascript的setTimeout()函数。
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
您可以查看此链接:Calling a function every 60 seconds,了解有关每隔X秒调用一次函数的详细信息。