Skip to content

Instantly share code, notes, and snippets.

@DaniruKun
Created July 10, 2023 12:54
Show Gist options
  • Save DaniruKun/1368a9e1e70757bcc20f8add02d7fd1a to your computer and use it in GitHub Desktop.
Save DaniruKun/1368a9e1e70757bcc20f8add02d7fd1a to your computer and use it in GitHub Desktop.
Presigned upload example in Ruby
#!/usr/bin/env ruby
require "aws-sdk-s3"
require "net/http"
# Creates a presigned URL that can be used to upload content to an object.
#
# @param bucket [Aws::S3::Bucket] An existing Amazon S3 bucket.
# @param object_key [String] The key to give the uploaded object.
# @return [URI, nil] The parsed URI if successful; otherwise nil.
def get_presigned_url(bucket, object_key)
url = bucket.object(object_key).presigned_url(:put)
puts "Created presigned URL: #{url}"
URI(url)
rescue Aws::Errors::ServiceError => e
puts "Couldn't create presigned URL for #{bucket.name}:#{object_key}. Here's why: #{e.message}"
end
def run_demo
bucket_name = "scs-presigned-upload-test"
object_key = "my-file.txt"
object_content = "This is the content of my-file.txt."
bucket = Aws::S3::Bucket.new(bucket_name)
presigned_url = get_presigned_url(bucket, object_key)
return unless presigned_url
response = Net::HTTP.start(presigned_url.host) do |http|
http.send_request("PUT", presigned_url.request_uri, object_content, "content_type" => "")
end
case response
when Net::HTTPSuccess
puts "Content uploaded!"
else
puts response.value
end
end
run_demo if $PROGRAM_NAME == __FILE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment