Rails -nokogiri GEM: 检测URL中图像的MIME类型

3
我使用gem nokogiri来获取img标签的src值。 有时url没有显示文件名及其扩展名。
因此,我尝试按如下方式检测图像MIME类型:
MIME::Types.type_for("http://web.com/img/12457634").first.content_type # => "image/gif"

但是它显示错误:
undefined method `content_type' for nil:NilClass (NoMethodError)

有什么解决方案吗?


1
是的,它运行得非常好。 - Kaleem Ullah
太好了 :) 很高兴听到这个消息 :) - K M Rakibul Islam
1个回答

5
您会看到以下错误信息:

undefined method `content_type' for nil:NilClass (NoMethodError)

因为MIME::Types.type_for("http://web.com/img/12457634").first对象有时会是nil

要避免这个问题,可以这样做:

MIME::Types.type_for("http://web.com/img/12457634").first.try(:content_type)

因此,如果它是nil,它不会使您的程序崩溃。如果它不是nil,则可以获得正确的content_type

或者,为了检查使用Net::HTTP的图像的Content-Type头,您可以编写如下方法:

def valid_image_exists?(url)
    url = URI.parse(url)
    Net::HTTP.start(url.host, url.port) do |http|
      return http.head(url.request_uri)['Content-Type'].start_with? 'image'
    end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接