Last active
July 5, 2021 19:52
-
-
Save diamondap/9134867 to your computer and use it in GitHub Desktop.
Overriding S3 HTTP Headers (Ruby)
This file contains 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
# Given an S3 URL, this returns a signed S3 url that will force the browser | |
# to download the file rather than opening it in the browser window. The key | |
# is to add response-content-disposition to the query string, which tells S3 | |
# to send the content-disposition header you specify. S3 will respect this | |
# parameter only if the URL is signed. You can override other S3 headers such | |
# as content-type using this same method. See: | |
# | |
# http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html | |
# | |
def s3_download_url(url) | |
s3_key = URI(url).path | |
filename = s3_key.split('/')[-1] | |
disposition = "response-content-disposition=attachment;filename=#{filename}" | |
expires = 60.minutes.from_now.utc.to_i | |
query_string_char = url.include?('?') ? '&' : '?' | |
string_to_sign = "GET\n\n\n#{expires}\n#{s3_key}#{query_string_char}#{disposition}" | |
digest = OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), | |
S3FileField.config.secret_access_key, | |
string_to_sign) | |
signature = Base64.encode64(digest).gsub("\n", "").gsub('+', '%2B') | |
"#{url}#{query_string_char}#{disposition}&AWSAccessKeyId=#{AWS.config.access_key_id}&Expires=#{expires}&Signature=#{signature}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you use the aws-sdk, you can do this: