2009-12-18 61 views
2

我正在循环访问外部网站托管的图像的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" 

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

回答

4

难道你不能做一个简单的图像请求,并检查它的404?它不完美,但会赶上散装。取决于你运行它的频率。如果您没有直接访问服务器上的文件来检查,那么HTTP请求是唯一的方法。为了提高速度,你可以做一个仅头部请求。将需要一个代码示例,让我挖你一个...

取决于你的服务器将返回,如果你可以得到标题,你只是得到一个标准的404页,然后你可以检查内容长度确保它对于图像来说不够大,这听起来有点冒险,但会起作用(之后有更好的方法)。例如:

(从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状态而不需要执行整个请求(请参阅上面链接的文档中的请求方法以了解详细信息)。

虽然希望有所帮助。

9

我不认为有可能检查远程图像的可用性没有定期请求,皮特描述。

但可能是你找我用过一次(使用jQuery)有用的技巧:

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

在错误事件中,你可以替换图像URL中的域名。

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

+0

我很欣赏这个输入。不幸的是,这次我需要在服务器端完成所有这些工作,但是将来会考虑到这一点。 – btw 2009-12-18 20:39:36

+0

感谢一个很好的客户端修复罗马。将这个添加到工具箱,谢谢;) – 2009-12-21 11:24:45

+0

谢谢,漂亮的黑客 – Emmanuel 2012-12-18 16:56:39