How do I check if a file exists in AWS S3 bucket using Rails3

Amazon S3 Online Service 123
Social sharing

Amazon_S3_Online_Service-123

Introduction

Amazon S3 provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web. While uploading a file to S3 we need to check whether the file exists to avoid any data duplication.

Steps to check the presence of a file

Step#1

Add the below in your gem file,

gem 'aws-s3'

Then run the bundle,

bundle install

Step#2

Modify your model as,

require 'aws/s3'

def  is_file_exist?
AWS::S3::Base.establish_connection!( :access_key_id => 'S3_KEY', :secret_access_key => 'S3_SECRET')
return AWS::S3::S3Object.exists? attachment_id, "<YOUR_BUCKET_NAME>”
end

It is preferred to have the s3 credentials on the config folder and use it from the config file.

Step#3

Now modify your controller where you want to check the existence of the file,

current_user.is_file_exist? #return true if exists

Easy method to avoid data redundancy in secured AWS S3.

Read Also: How to use Amazon S3 Bucket with Paperclip to store images in Rails3

I hope you find this useful. If you want to develop application in rails or want to deploy app in AWS cloud, then Andolasoft is the ideal and cost savvy option for you.  Have something to add to this topic? Share it in the comments.

Your recently viewed posts:

Jayadev Das - Post Author

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘About Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box