Created
March 6, 2025 22:50
-
-
Save neohunter/d3dc495f48ec395a011fdbfb743cca59 to your computer and use it in GitHub Desktop.
aws s3 presigned url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'aws-sdk-s3' | |
# Configure AWS Credentials (using environment variables is recommended) | |
Aws.config.update({ | |
region: 'YOUR_AWS_REGION', # e.g., 'us-west-2' | |
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']) | |
}) | |
# S3 Bucket and Object Details | |
bucket_name = 'YOUR_S3_BUCKET_NAME' | |
object_key = 'path/to/your/object.pdf' # The path of the object in your S3 bucket | |
# Create an S3 Client | |
s3 = Aws::S3::Client.new | |
# Generate a Pre-signed URL | |
begin | |
presigned_url = s3.presigner.presigned_url( | |
:get_object, # Operation to perform (in this case, get the object) | |
bucket: bucket_name, | |
key: object_key, | |
expires_in: 3600, # Link expires in 1 hour (3600 seconds) | |
response_content_disposition: "attachment;filename=\"downloaded_file.pdf\"", #Forces download | |
response_content_type: "application/pdf" #Sets the correct content type | |
) | |
puts "Pre-signed URL: #{presigned_url}" | |
# if its a rails controller | |
# redirect_to presigned_url | |
rescue Aws::S3::Errors::NoSuchBucket => e | |
puts "Error: Bucket '#{bucket_name}' does not exist." | |
rescue Aws::S3::Errors::NoSuchKey => e | |
puts "Error: Object '#{object_key}' does not exist in bucket '#{bucket_name}'." | |
rescue StandardError => e | |
puts "An error occurred: #{e.message}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment