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?
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With