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

Kal*_*lah 3 html ruby mime ruby-on-rails

我正在使用 gemnokogiri来废弃img标签src值。有时url不显示带扩展名的图像文件名。

所以我试图检测图像MIME类型如下:

MIME::Types.type_for("http://web.com/img/12457634").first.content_type # => "image/gif"
Run Code Online (Sandbox Code Playgroud)

但它显示错误:

undefined method `content_type' for nil:NilClass (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

有什么解决办法吗?

K M*_*lam 5

您收到此错误:

undefined method `content_type' for nil:NilClass (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

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

为避免此问题,请执行以下操作:

MIME::Types.type_for("http://web.com/img/12457634").first.try(:content_type)
Run Code Online (Sandbox Code Playgroud)

因此,如果它是nil. 如果不是nil,你会得到正确的content_type

或者,要Content-Type使用来检查图像的标题Net::HTTP,您可以编写如下方法:

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
Run Code Online (Sandbox Code Playgroud)