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