Check if a file exists on AWS S3 path using aws-sdk gem

Viewed 4164

I am trying to check whether a particular pdf file exists on AWS S3 using aws-sdk gem (version 2) inside ruby on rails application.

I have the AWS connection established and currently using exists? method:

puts @bucket.objects(prefix:"path/sample_100.pdf").exists?

on running the above statement, I get the below no method error:

undefined method 'exists?' for Aws::Resources::Collection

Checked few documents but of not much help. Is there any other way to achieve the same?

Thanks in advance

3 Answers

As mentioned by Bruno, you can use head_object to get info on the file, without actually fetching it. If it is not found (or other problems, such as permissions), an exception will be raised. So if head_object returns, the file exists.

Here's a file that exists:

> head = s3.head_object(bucket: bucket, key: path)
 => #<struct Aws::S3::Types::HeadObjectOutput last_modified=2020-06-05 16:18:05 +0000, content_length=553, etc...>

And here's one that does not exist, and the exception it raises:

> path << '/not-really'
 => "example/file/not-really"
> head = s3.head_object(bucket: bucket, key: path)

Aws::S3::Errors::NotFound

Traceback (most recent call last):
        1: from (irb):18
Aws::S3::Errors::NotFound ()

And here's how you can roll your own s3_exists? method:

def s3_exists?(bucket, path)
  s3.head_object(bucket: bucket, key: path)
  true 
rescue
  false
end
Related