Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 422
Ph0en1x Avatar asked Apr 18 '13 23:04

Ph0en1x


People also ask

How do you check if a file exists from a URL?

The file_exists() function in PHP, is used to check if a file or directory exists on the server. But the file_exists() function will not usable if you want to check the file existence on the remote server. The fopen() function is the easiest solution to check if a file URL exists on a remote server using PHP.

How to check if file exist in html?

The exists() method of the File object returns a boolean value based on the existence of the file in which it was invoked. If the file exists, the method returns true. It returns false if the file does not exist.

How to check if file exists in jQuery?

Approach 1: Use ajax() method of jQuery to check if a file exists on a given URL or not. The ajax() method is used to trigger the asynchronous HTTP request. If the file exists, ajax() method will in turn call ajaxSuccess() method else it will call Error function.


2 Answers

If you want to use 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 
like image 63
Shawn Balestracci Avatar answered Nov 13 '22 19:11

Shawn Balestracci


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.

like image 31
JoshEmory Avatar answered Nov 13 '22 19:11

JoshEmory