用自定义图像替换破碎的外部图像

我正在遍历在外部站点托管的一系列URL图像字符串。

它看起来像这样:

def get_image_urls image_url_array.each do |image_url| puts image_tag image_url end end 

这将返回外部站点上托管的图像的URL。 问题是,其中一些图像可能会被破坏(404)。 例如:

 get_image_urls # These would return image_tags, but for brevity... => "http://sofzh.miximages.com/ruby-on-rails/1.jpg" "http://sofzh.miximages.com/ruby-on-rails/2.jpg" "http://sofzh.miximages.com/ruby-on-rails/3.jpg" # <-- (Broken: 404) "http://sofzh.miximages.com/ruby-on-rails/4.jpg" "http://sofzh.miximages.com/ruby-on-rails/5.jpg" # <-- (Broken: 404) 

我要做的是将损坏图像的URL字符串替换为我自己网站上托管的“缺失”图像。 所以使用上面的例子,3.jpg和5.jpg被打破了,我想要返回这样的东西:

 get_image_urls # These would return image_tags, but for brevity... => "http://sofzh.miximages.com/ruby-on-rails/1.jpg" "http://sofzh.miximages.com/ruby-on-rails/2.jpg" "http://mysite.com/images/missing.png" "http://sofzh.miximages.com/ruby-on-rails/4.jpg" "http://mysite.com/images/missing.png" 

有没有一种简单的方法可以解决这个问题? 非常感谢提前。

你不能对图像做一个简单的请求,检查它是否是404? 它不完美,但会占上风。 取决于你运行它的频率。 如果您无法直接访问服务器上的文件进行检查,那么HTTP请求是唯一的方法。 对于速度,您可以执行仅标头请求。 需要一个代码示例,让我挖出一个…

取决于你的服务器将返回什么,如果你可以得到标题,你只是得到一个标准的404页面然后你可以检查内容长度,以确保它不够大的图像,听起来有点hacky但会工作(theres事后更好的方式)。 就像是:

(从http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html#M000682获取并修改)。

 response = nil Net::HTTP.start('www.example.com', 80) {|http| response = http.head('/myimage.html') } # Assume anything with a content-length greater than 1000 must be an image? # You will need to tweek/tune this to your server and your definition of what a good image is p "Good image" unless response['content-length'] < 1000 

或者,您可以(并且应该以正确的方式执行)获取HTTP状态消息,因为服务器的确定方式告诉您图像是否存在。 唯一的麻烦是您可能必须下载整个内容,因为我不知道如何快速获取HTTP状态而不执行整个请求(请参阅上面链接的doc中的请求方法以获取详细信息)。

希望有所帮助。

我不认为有可能检查远程图像的可用性,而不像Pete描述的那样定期请求。

但是你可能会找到我曾经使用过的有用技巧(使用jquery):

 $('img').error(function(){ $(this).attr('src', '<<>>'); }); 

在错误事件上,您可以替换图像URL上的主机。

此外,您可以通过AJAXpost从客户端收集此信息到主机,并在发生一些此类错误后 – 使用Pete方法检查。 它将从根本上减少所需的检查量。