1

I recently implemented file uploading using carrier-wave with Amazon S3 storage.

I want to generate, or make available, the S3 URL only for one hour. After that the link should expire.

How can I do this using carrier-wave?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ferdy
  • 41
  • 9

1 Answers1

1

The way to handle this is to use a presigned URL for the S3 file. Once you upload the file using carrier wave, you access the actual S3 URL and use AWS::S3 to presign it with an expiration time. For example, if the key (file name) in your S3 bucket is "my_file", you could do this:

# Your Model
def presigned_url
  s3 = AWS::S3.new
  bucket = s3.buckets["MyBucket"]
  object = bucket.objects["my_file"]
  object.url_for(:read, secure:true, expires:1.hour)
end

The URL returned will be valid for 1 hour and then will never work again.

To use this, you will need to include the aws-s3 gem in your Gemfile:

# Gemfile
gem "aws-s3"
Troy
  • 5,319
  • 1
  • 35
  • 41
  • 1
    thanks for the response.... i used 'config.fog_authenticated_url_expiration = 60 # (in seconds) => 10 minutes' to expire the ur.now when i click the url i am getting ** AccessDenied Request has expired F936007949CDA7C9 2014-01-30T15:46:27Z gvErTgANourjWZB0kIROqcbiUhDgGsJkXdAQvnsXANixIlMbSSDeu/zTxlIZ23r+ 2014-01-30T15:46:30Z**xml error form amazon.but i wants to hand this error to display error message to the user.can you help me? – ferdy Jan 30 '14 at 15:51
  • 60 is only 1 minute - did you mean 600? – Troy Jan 31 '14 at 16:34
  • Please ask another question with a code sample to get help on how to show this error to the user. – Troy Jan 31 '14 at 16:35
  • how can i access the file again once the url is expired. I have asked the question here http://stackoverflow.com/questions/24805094/how-to-access-the-file-from-amazon-s3-expired-url but didnt get the answer – Bloomberg Jul 17 '14 at 16:55
  • The answer there is correct. The URL is only valid until it expires. Once it has expired, you can no longer use it. The file is still stored safely, but the presigned url is useless. You could run that code again to create a new temporary URL. – Troy Jul 22 '14 at 05:15