Does Image URL exist?

Hello everyone, I’ve been trying to find a code that will let me see if
an image URL that I enter exists, but am having trouble.

Basically I just need something that will tell me yes or no if the image
URL exists or not (meaning the Image is uploaded on the server).

Any suggestions?

On Monday 15 October 2007, Tj Superfly wrote:

Hello everyone, I’ve been trying to find a code that will let me see
if
an image URL that I enter exists, but am having trouble.

Basically I just need something that will tell me yes or no if the
image
URL exists or not (meaning the Image is uploaded on the server).

If you don’t care whether it’s an image not, this is relatively easy,
all you need to do is ask the server if the path exists (response code
200) or if the path doesn’t (response code 404). You don’t need to
even download any of the content of the file.

If you care whether the path exists and it’s an image, you’ll need to
check its mime type. If you’re pretty sure the server is doing the
right thing you can do this with a a HTTP head and not transfer the
contents. If you really want to make sure it’s an image you’ll have to
download it and verify the file.

I think checking with an HTTP head that the content-type is an image
content type should be enough, so something like this should do:

require ‘uri’
require ‘net/http’

url = URI.parse(“http://example.com/images/yer_img_here.foo”)

Net::HTTP.start(url.host, url.port) do |http|
response = http.head(url.path)
case response
when Net::HTTPSuccess, Net::HTTPRedirection
case response.content_type
when “image/png”, “image/gif”, “image/jpeg”
puts “ok”
else
puts “nope”
end
else
puts “nope”
end
end

Ben

Worked, like a charm. :smiley: Thank you very much.

Now I’m off to experiment with it.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs