Share a private S3 object

If you upload a file to S3 and set ACL as private, it cannot be accessed from public or anyone other than the file owner.

acl: 'private'

To share the file temporary with other parties (E.g. For a client to download the file), you have to create a presigned URL.

signer = Aws::S3::Presigner.new(
    client: client,
    expires_in: 120

)
url = signer.presigned_url(:get_object, bucket: s3_bucket_name, key: 'filename.txt')

puts url

The expires_in option defines how long this presigned URL valid.

In fact, you can also generate a presigned URL to complete other operation such as uploading a file. Example:

object = Aws::S3::Object.new(
	client: client,
	bucket_name: s3_bucket_name,
	key: 'filename'
)

url = obj.presigned_url(:put)
# This is on the other

remote_url = URI.parse(url)
body = "Hello World"

Net::HTTP.start(remote_url.host) do |http|
http.send_request("PUT", remote_url.request_uri, body, {
"content-type" => "text/plain", "cache-control" => "public, max-age=604800" }) end

AI Summary
Chrome On-device AI 2024-07-20 05:03:56

Share Article