Reputation: 21
This is the cloudinary link.
http://res.cloudinary.com/dm1hql92i/raw/upload/c_fill,h_200,w_200/%7B%7D
I want to check if the image exists or not in that link with ruby.
Upvotes: 1
Views: 2456
Reputation: 1639
For some reason Ganesh's answer didnt work for me, here is my approach:
def image_exists?(url)
response = {}
uri = URI(url)
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end
return response.content_type.starts_with?("image")
end
Upvotes: 1
Reputation: 2004
You will come to know that by checking Content-Type
which is present in HTTP header
Please refer following code snippet.
require 'net/http'
require 'uri'
def image_exists?(url)
url = URI.parse(url)
http = Net::HTTP.start(url.host, url.port)
http.head(url.request_uri)['Content-Type'].start_with? 'image'
end
url = "http://res.cloudinary.com/dm1hql92i/raw/upload/c_fill,h_200,w_200/%7B%7D"
image_exists?(url)
=> true
url = "http://guides.rubyonrails.org/getting_started.html"
image_exists?(url)
=> false
Upvotes: 3