validation远程映像实际上是ruby中的映像文件?

我试图找出如何validation我正在为载波提供的内容实际上是一个图像。 我得到我的图片url的来源并没有让我回到所有现场url。 一些图像不再存在。 不幸的是,它并没有真正返回正确的状态代码或任何东西,因为我使用一些代码来检查远程文件是否存在并且是否通过了该检查。 所以现在只是为了安全起见,我想要一种方法来validation我在恢复有效的图像文件之前继续下载它。

这是我用于参考的远程文件检查代码,但我更喜欢能够识别文件是图像的东西。

require 'open-uri' require 'net/http' def remote_file_exists?(url) url = URI.parse(url) Net::HTTP.start(url.host, url.port) do |http| return http.head(url.request_uri).code == "200" end end 

我会检查服务是否在Content-Type HTTP标头中返回正确的mime类型。 ( 这是一个mime类型列表 )

例如,StackOverflow主页的Content-Type是text/html; charset=utf-8 text/html; charset=utf-8 ,您的重力图像的内容类型为image/png

要使用Net :: HTTP检查ruby中的image的Content-Type标头,您将使用以下内容:

 def remote_file_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 

Rick Button的答案对我有用,但我需要添加SSl支持:

 def self.remote_image_exists?(url) url = URI.parse(url) http = Net::HTTP.new(url.host, url.port) http.use_ssl = (url.scheme == "https") http.start do |http| return http.head(url.request_uri)['Content-Type'].start_with? 'image' end end 

我最终使用了HTTParty。 来自Rick Button的.net请求答案一直在超时。

  def remote_file_exists?(url) response = HTTParty.get(url) response.code == 200 && response.headers['Content-Type'].start_with? 'image' end 

https://github.com/jnunemaker/httparty