html - rails -nokogiri GEM : Detect MIME type of image in URL

标签 html ruby-on-rails ruby mime

我正在使用 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)

有什么解决办法吗?

最佳答案

你得到这个错误:

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 header ,您可以编写如下方法:

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

关于html - rails -nokogiri GEM : Detect MIME type of image in URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32456746/

相关文章:

html - <p> 中的文本不能垂直居中

ruby-on-rails - 这个渲染方法在哪里定义的?

javascript - 如何使用 ajax 在 Rails 中分配和访问 javascript 变量

ruby-on-rails - Rails Elasticsearch-多个过滤条件

ruby - 用于解析国际电话号码的最佳 ruby gem 是什么?

ruby - MailCatcher 不适用于 VM 上的 rbenv

javascript - document.getElementsByClassName().innerHTML 总是返回 "undefined"

javascript - 单次点击多个ID

javascript - 如何使 div 像图像中的盒子一样?

ruby-on-rails - 水计量应用程序的建模数据