btw*_*btw 2 ruby ruby-on-rails image http http-status-code-404
我正在遍历在外部站点托管的一系列URL图像字符串.
它看起来像这样:
def get_image_urls
image_url_array.each do |image_url|
puts image_tag image_url
end
end
Run Code Online (Sandbox Code Playgroud)
这将返回外部网站上托管的图像的URL.问题是,其中一些图像可能会被破坏(404).例如:
get_image_urls
# These would return image_tags, but for brevity...
=> "http://someothersite.com/images/1.jpg"
"http://someothersite.com/images/2.jpg"
"http://someothersite.com/images/3.jpg" # <-- (Broken: 404)
"http://someothersite.com/images/4.jpg"
"http://someothersite.com/images/5.jpg" # <-- (Broken: 404)
Run Code Online (Sandbox Code Playgroud)
我要做的是将损坏图像的URL字符串替换为我自己网站上托管的"缺失"图像.所以使用上面的例子,3.jpg和5.jpg被打破了,我想要返回这样的东西:
get_image_urls
# These would return image_tags, but for brevity...
=> "http://someothersite.com/images/1.jpg"
"http://someothersite.com/images/2.jpg"
"http://mysite.com/images/missing.png"
"http://someothersite.com/images/4.jpg"
"http://mysite.com/images/missing.png"
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以解决这个问题?非常感谢提前.
小智 10
我不认为有可能检查远程图像的可用性,而不像Pete描述的那样定期请求.
但是你可能会找到我曾经使用过的有用技巧(使用jquery):
$('img').error(function(){
$(this).attr('src', '<<<REPLACE URL>>>');
});
Run Code Online (Sandbox Code Playgroud)
在错误事件上,您可以替换图像URL上的主机.
此外,您可以通过AJAX帖子从客户端收集此信息到主机,并在发生一些此类错误后 - 使用Pete方法检查.它将从根本上减少所需的检查量.