BetuUuUu

upload_helper.rb

Nov 12th, 2013
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.98 KB | None | 0 0
  1. module UploadHelper
  2.   def s3_uploader_form(options = {}, &block)
  3.     uploader = S3Uploader.new(options)
  4.     form_tag(uploader.url, uploader.form_options) do
  5.       uploader.fields.map do |name, value|
  6.         hidden_field_tag(name, value)
  7.       end.join.html_safe + capture(&block)
  8.     end
  9.   end
  10.  
  11.   class S3Uploader
  12.     def initialize(options)
  13.       @options = options.reverse_merge(
  14.         id: "fileupload",
  15.         aws_access_key_id: ENV["AWS_ACCESS_KEY_ID"],
  16.         aws_secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"],
  17.         bucket: ENV["AWS_S3_BUCKET"],
  18.         acl: "public-read",
  19.         expiration: 10.hours.from_now,
  20.         max_file_size: 2.megabytes,
  21.         as: "file"
  22.       )
  23.     end
  24.  
  25.     def form_options
  26.       {
  27.         id: @options[:id],
  28.         method: "post",
  29.         authenticity_token: false,
  30.         multipart: true,
  31.         data: {
  32.           post: @options[:post],
  33.           as: @options[:as]
  34.         }
  35.       }
  36.     end
  37.  
  38.     def fields
  39.       {
  40.         :key => key,
  41.         :acl => @options[:acl],
  42.         :policy => policy,
  43.         :signature => signature,
  44.         "AWSAccessKeyId" => @options[:aws_access_key_id],
  45.       }
  46.     end
  47.  
  48.     def key
  49.       @key ||= "uploads/#{SecureRandom.hex}/${filename}"
  50.     end
  51.  
  52.     def url
  53.       "https://#{@options[:bucket]}.s3.amazonaws.com/"
  54.     end
  55.  
  56.     def policy
  57.       Base64.encode64(policy_data.to_json).gsub("\n", "")
  58.     end
  59.  
  60.     def policy_data
  61.       {
  62.         expiration: @options[:expiration],
  63.         conditions: [
  64.           ["starts-with", "$utf8", ""],
  65.           ["starts-with", "$key", ""],
  66.           ["content-length-range", 0, @options[:max_file_size]],
  67.           {bucket: @options[:bucket]},
  68.           {acl: @options[:acl]}
  69.         ]
  70.       }
  71.     end
  72.  
  73.     def signature
  74.       Base64.encode64(
  75.         OpenSSL::HMAC.digest(
  76.           OpenSSL::Digest::Digest.new('sha1'),
  77.           @options[:aws_secret_access_key], policy
  78.         )
  79.       ).gsub("\n", "")
  80.     end
  81.   end
  82. end
Add Comment
Please, Sign In to add comment