【问题标题】:Replacing Broken External Images With Custom Image用自定义图像替换损坏的外部图像
【发布时间】:2010-12-28 02:10:52
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 感谢您的意见。不幸的是,这一次我需要在服务器端完成这一切,但以后会牢记这一点。
    • 感谢一个很好的客户端修复 Roman。将其添加到工具箱中,谢谢 ;)
    【解决方案2】:

    你不能对图像做一个简单的请求并检查它是否是 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 状态的方法(有关详细信息,请参阅上面链接的文档中的请求方法)。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 1970-01-01
      • 2014-08-08
      • 2012-02-09
      • 2015-12-11
      • 1970-01-01
      • 2014-06-28
      • 2013-04-20
      相关资源
      最近更新 更多