KevinU
KevinU

Reputation: 41

How to include Amazon S3 Content-MD5 request header with Rails S3DirectUpload gem?

I am building a Rails 4 app with admin uploads of large files to Amazon S3. To validate the transfer of the large files, I would like to include the Content-MD5 field in the request header per the Amazon docs:

http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html

I started with Paperclip + S3 and the MD5 verification is working:

has_attached_file :file,
                :storage => :s3,
                :bucket => AppSetting.s3_bucket,
                :s3_credentials => Proc.new{|a| a.instance.s3_credentials },
                :s3_permissions => :private,
                :s3_headers => Proc.new{|a| a.s3_headers },
                :path => "uploads/:id/:basename.:extension"

def s3_credentials
  {:access_key_id => AppSetting.aws_access_key_id, :secret_access_key => AppSetting.aws_secret_access_key}
end

# md5sum is a value entered by the user as a string (hex notation)
# ex: "7d592a3129ab6a867cf6e2eb60f9ef83"
#
def encoded_md5sum
  [[md5sum].pack("H*")].pack("m0")
end

def s3_headers
  {:content_md5 => encoded_md5sum}
end

With Paperclip, the large file is first uploaded to my server, then transferred to Amazon S3. This blocks the Rails process and consumes redundant bandwidth, so I am trying to use the S3UploadDirect gem to upload the file directly the S3 bucket:

https://github.com/waynehoover/s3_direct_upload

This gem is a wrapper around the code from Railscasts episode 383 and uses jquery-fileupload-rails for the actual upload:

<%= s3_uploader_form callback_url: "#{AppSetting.host_base_url}/admin/uploads",
                 callback_method: "POST",
                 callback_param: "upload[file_url]",
                 key: "uploads/{timestamp}-{unique_id}-#{SecureRandom.hex}/${filename}",
                 key_starts_with: "uploads/",
                 acl: "private",
                 bucket: AppSetting.s3_bucket,
                 aws_access_key_id: AppSetting.aws_access_key_id,
                 aws_secret_access_key: AppSetting.aws_secret_access_key,
                 max_file_size: 5.gigabytes,
                 id: "s3-uploader",
                 class: "upload-form",
                 data: {:key => :val} do %>
  <%= file_field_tag :file, multiple: true %>
<% end %>

<script id="template-upload" type="text/x-tmpl">
  <div id="file-{%=o.unique_id%}" class="upload">
   {%=o.name%}
   <div class="progress"><div class="bar" style="width: 0%"></div></div>
 </div>
</script> 

I can upload the file, but I cannot figure out how to pass the Content-MD5 information into the upload request header.

Upvotes: 1

Views: 457

Answers (0)

Related Questions