had*_*ees 11 ruby image ruby-on-rails-3 carrierwave
我试图找出如何验证我正在为载波提供的内容实际上是一个图像.我得到我的图片网址的来源并没有让我回到所有现场网址.一些图像不再存在.不幸的是,它并没有真正返回正确的状态代码或任何东西,因为我使用一些代码来检查远程文件是否存在并且是否通过了该检查.所以,现在只是为了安全起见,我想要一种方法来验证我在获取有效的图像文件之前继续下载它.
这是我用于参考的远程文件检查代码,但我更喜欢能够识别文件是图像的东西.
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
Run Code Online (Sandbox Code Playgroud)
Ric*_*ton 11
我会检查服务是否在Content-Type HTTP标头中返回正确的mime类型.(这是一个mime类型列表)
例如,StackOverflow主页text/html; charset=utf-8的Content-Type是,您的重力图像的Content-Type是image/png
要image使用Net :: HTTP 检查ruby中的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
Run Code Online (Sandbox Code Playgroud)
小智 9
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
Run Code Online (Sandbox Code Playgroud)
我最终为此使用了 HTTParty。Rick Button 的 .net 请求应答始终超时。
def remote_file_exists?(url)
response = HTTParty.get(url)
response.code == 200 && response.headers['Content-Type'].start_with? 'image'
end
Run Code Online (Sandbox Code Playgroud)
https://github.com/jnunemaker/httparty