Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amazon s3 - ruby. Get the URL of the resource that was just uploaded

I have the following code that is used to upload a local file to Amazon S3 Bucket:

require 'aws/s3'
module AmazonS3

  def self.upload_file(local_file)
    bucket_name = "bucketfortest"

      s3 = AWS::S3.new(
        :access_key_id     => ENV["AMAZON_ACCESS_KEY"], 
        :secret_access_key => ENV["AMAZON_SECRET_KEY"] 
      )


    key = File.basename(local_file)

    amazon_object = s3.buckets[bucket_name].objects[key].write(:file => local_file)
    return amazon_object #How can I get the URL of the object here?

  end
end

I based this code on: Upoad file S3 I am trying to find out a way to get the URL of the object that was just uploaded, but I fail to find what is it. I tried .url , but that gives me an Undefined Method. I fail to see anything in the docs either.

like image 347
Hommer Smith Avatar asked Oct 23 '13 22:10

Hommer Smith


People also ask

How do I get my S3 upload URL?

You can get the resource URL either by calling getResourceUrl or getUrl . AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder. defaultClient(); s3Client. putObject(new PutObjectRequest("your-bucket", "some-path/some-key.

How do I get a Presigned URL?

To create a valid pre-signed URL for your object, you must provide your security credentials, specify a bucket name, an object key, specify the HTTP method (for instance the method is "GET" to download the object) and expiration date and time. Anyone who receives the pre-signed URL can then access the object.

How do I get a Presigned URL on AWS?

To generate a pre-signed URL, use the Presign method on the request object. You must set an expiration value because the AWS SDK for Go doesn't set one by default. The following example generates a pre-signed URL that enables you to temporarily share a file without making it public.

How does Presigned URL work S3?

Generating a presigned URL for uploading objects When you use the URL to upload an object, Amazon S3 creates the object in the specified bucket. If an object with the same key that is specified in the presigned URL already exists in the bucket, Amazon S3 replaces the existing object with the uploaded object.


2 Answers

I haven't used the Ruby AWS SDK at all but it looks like you could do this:

Get the public URL:

return amazon_object.public_url

Or a signed URL for a private object:

return amazon_object.url_for(:read, :expires => 10*60)
like image 61
Matt Cooper Avatar answered Oct 26 '22 13:10

Matt Cooper


You know the url because it's the same url as the local file's filename. So you can compose the url from the filename and the bucket name, without getting any info from S3 other than success.

like image 40
Victor Pudeyev Avatar answered Oct 26 '22 14:10

Victor Pudeyev