Using S3 Presigned-URL for upload a file that will then have public-read access

前端 未结 2 1920
梦毁少年i
梦毁少年i 2021-01-04 09:20

I am using Ruby on Rails and AWS gem. I can get pre-signed URL for upload and download. But when I get the URL there is no file, and so setting acl to \'public-read\' on the

2条回答
  •  花落未央
    2021-01-04 10:19

    You have two options:

    • Set the ACL on the object to 'public-read' when you PUT the object. This allows you to use the public url without a signature to GET the object.
    • Let the ACL on the object default to private and provide pre-signed GET urls for users. These expire, so you have to generate new URLs as needed. A pre-signed URL allows someone to send GET request to the object without credentials themselves.

    Upload a public object and generate a public url:

    require 'aws-sdk'
    
    s3 = Aws::S3::Resource.new
    s3.bucket('bucket-name').object('key').upload_file('/path/to/file', acl:'public-read')
    s3.public_url
    #=> "https://bucket-name.s3.amazonaws.com/key"
    

    Upload a private object and generate a GET url that is good for 1-hour:

    s3 = Aws::S3::Resource.new
    s3.bucket('bucket-name').object('key').upload_file('/path/to/file')
    s3.presigned_url(:get, expires_in: 3600)
    #=> "https://bucket-name.s3.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&..."
    

提交回复
热议问题