Ph0en1x
Ph0en1x

Reputation: 10067

How do I check if a file exists using its URL without downloading it?

I need to write code which will determine if a file exists by checking its URL.

Currently I implement this:

error_code = 400;
response = Net::HTTP.get_response(URI(url));
return response.code.to_i < error_code;

But, it's not working right because each time it downloads the file, which is really slow if I have big files or a lot of them.

How do I determine if a file exists on the remote side without downloading it?

Upvotes: 22

Views: 12254

Answers (3)

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

If you want to use Rubys included Net::HTTP then you can do it this way:

uri = URI(url)

request = Net::HTTP.new uri.host
response= request.request_head uri.path
return response.code.to_i == 200

Upvotes: 33

JoshEmory
JoshEmory

Reputation: 644

With the rest-client gem installed, do something like this

require "rest-client"
 
begin
  exists = RestClient.head("http://google.com").code == 200
rescue RestClient::Exception => error
  exists = (error.http_code != 404) 
end

Then "exists" is a boolean depending whether if it exists or not. This will only get the header information, not the file, so it should be the same for small or big files.

Upvotes: 6

the Tin Man
the Tin Man

Reputation: 160551

I'd write it this way:

require 'net/http'

ERROR_CODE = 400

response = Net::HTTP.start('www.example.net', 80) do |http|
  http.request_head('/index.html') 
end

puts response.code.to_i < ERROR_CODE

Which outputs true because I got a 302 for the response.code.

Upvotes: 2

Related Questions