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