Ekta Verma
Ekta Verma

Reputation: 221

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

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

Upvotes: 9

Views: 6577

Answers (3)

David Hempy
David Hempy

Reputation: 6187

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

Upvotes: 6

CV-Gate
CV-Gate

Reputation: 1170

I'd recommend you to use the much simpler S3 gem: https://github.com/qoobaa/s3 If you only need to deal with S3. You'll be able to do it this way:

object = bucket.objects.find("example.pdf")

Upvotes: 1

Bruno Reis
Bruno Reis

Reputation: 37822

I'm not a Ruby developer myself, but I might be able to suggest something.

The usual way to check whether an object exists in Amazon S3 is using the HEAD Object operation. Basically, it returns the metadata (but no content) of an object if it exists, or a 404 error if it doesn't. It's like GET Object, but without the contents of the object.

I just looked up in the AWS SDK for Ruby API Reference and found this method:

http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Client.html#head_object-instance_method

Take a look at that, it's probably what you are looking for.

Upvotes: 3

Related Questions