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

时间:2009-12-18 15:50:35

标签: ruby-on-rails ruby http image http-status-code-404

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

它看起来像这样:

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

将返回外部网站上托管的图片的网址。问题是,其中一些图像可能会被破坏(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)

我要做的是将损坏图像的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"

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

2 个答案:

答案 0 :(得分:10)

我不认为可以像Pete所描述的那样在没有定期请求的情况下检查远程图像的可用性。

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

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

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

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

答案 1 :(得分:4)

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

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

(从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状态(请参阅上面链接的文档中的请求方法以获取详细信息)。

希望有所帮助。