s3-upnow 0.2.0 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: c130dadc4b2ed0be86811b4b029c7539a3265cd8
4
- data.tar.gz: a8c1aba09a3f422360bbe1abdc5b58f151a7dab4
2
+ SHA256:
3
+ metadata.gz: 041a97c9289dd68106c4fd1696f7cfa55542e6f02faa1e90d69a4bb871e65265
4
+ data.tar.gz: a45b9f03c72ea6e1475db27424824fbdfe4a441980e0cfbdf451583c50da6b5e
5
5
  SHA512:
6
- metadata.gz: f3936e913d8dbeb45fea532dc0c1dbb7d6ce2871b404acfb8b685f8920a473b8bb336f87b525bca0fd18971af5b73c290a75b5bdab9791c8c9e0cf57904fbde0
7
- data.tar.gz: 136f94792ef3951b6e58212b6a42f460e42fca936bb6efc6c8a7c44c06797aebafefb422be88bf35f4a9adcba794d308bdce7e8d2de42b6cd542b70e136e9165
6
+ metadata.gz: f58f2ddc561a708f87f359a394433d201aea642fd31067df50f981c7193844ca71226b2504134ecbfae19a60dee9ef7900a85af77fa24ff9222763d89d464921
7
+ data.tar.gz: 3a116c2f0b3de222d172512271f4d2dca4dfd78727f20356fa4bca83be614ffcdae897d5ce708ce5661fedbd1603ff72a15736b85d8e271e85bd4daeef97b237
data/README.md CHANGED
@@ -2,10 +2,16 @@
2
2
 
3
3
  [![Build Status](https://travis-ci.org/cerdiogenes/s3-upnow.svg)](https://travis-ci.org/cerdiogenes/s3-upnow)
4
4
 
5
- Easily generate a form that allows you to upload directly to Amazon S3.
6
- Multi file uploading supported by jquery-fileupload.
5
+ This is a fork of [s3_direct_upload](https://github.com/waynehoover/s3_direct_upload).
7
6
 
8
- Code extracted from Ryan Bates' [gallery-jquery-fileupload](https://github.com/railscasts/383-uploading-to-amazon-s3/tree/master/gallery-jquery-fileupload).
7
+ It's also has code from [refile](https://github.com/elabs/refile), mainly
8
+ related with the frontend.
9
+
10
+ The general idea of this gem is to be backend agnostic. I'd liked how
11
+ s3_direct_upload interact with S3 and I'd liked how refile interact with the
12
+ form and the backend, so I made a hybrid.
13
+
14
+ For now it's only works with [paperclip](https://github.com/thoughtbot/paperclip).
9
15
 
10
16
  ## Installation
11
17
  Add this line to your application's Gemfile:
@@ -40,47 +46,57 @@ Make sure your AWS S3 CORS settings for your bucket look something like this:
40
46
  ```
41
47
  In production the AllowedOrigin key should be your domain.
42
48
 
43
- Add the following js and css to your asset pipeline:
49
+ Add the following js to your asset pipeline:
44
50
 
45
51
  **application.js.coffee**
46
52
  ```coffeescript
47
53
  #= require s3-upnow
48
54
  ```
49
55
 
50
- **application.css**
51
- ```css
52
- //= require s3-upnow_progress_bars
53
- ```
54
-
55
56
  ## Usage
56
- Create a new view that uses the form helper `s3_uploader_form`:
57
+ Create a new view that uses the form helper `s3_upnow_field`:
57
58
  ```ruby
58
- <%= s3_uploader_form callback_url: model_url, callback_param: "model[image_url]", id: "s3-uploader" do %>
59
- <%= file_field_tag :file, multiple: true %>
60
- <% end %>
59
+ = simple_form_for @model do |f|
60
+ = f.s3_upnow_field :avatar
61
+ = f.button :submit
61
62
  ```
62
63
 
63
- * It is required that the file_field_tag is named 'file'.
64
- * A unique :id should be added to file_field_tag if there is many 's3_uploader_form' in the page
64
+ It will create a file field as well a hidden field with `s3_key` suffix. The
65
+ code above will generate something like:
65
66
 
67
+ ``` html
68
+ <form action="/models" enctype="multipart/form-data" method="post">
69
+ <input name="model[avatar_s3_key]" type="hidden">
70
+ <input name="model[avatar]" type="file">
71
+ </form>
72
+ ```
73
+
74
+ As refile, it will also remove the name attribute of the file field on a
75
+ successful upload to S3, so it doesn't get submitted with your form. By the way,
76
+ this doesn't play well with remote forms. For now I use the following code to
77
+ handle this:
66
78
 
67
- Then in your application.js.coffee, call the S3Uploader jQuery plugin on the element you created above:
68
79
  ```coffeescript
69
- jQuery ->
70
- $("#s3-uploader").S3Uploader()
80
+ $(document).on('upload:success', 'form', (event) ->
81
+ input = $(event.target)
82
+ form = input.parents('form').clone()
83
+ form.find(input).remove()
84
+ $.rails.handleRemote(form)
85
+ )
71
86
  ```
72
87
 
73
- Optionally, you can also place this template in the same view for the progress bars:
74
- ```js+erb
75
- <script id="template-upload" type="text/x-tmpl">
76
- <div id="file-{%=o.unique_id%}" class="upload">
77
- {%=o.name%}
78
- <div class="progress"><div class="bar" style="width: 0%"></div></div>
79
- </div>
80
- </script>
81
- ```
88
+ I just have one field, and I want to submit it right after I receive the
89
+ upload:success event. I don't know how this will be used in frontends, so I
90
+ want to have minimal policies for now. So, be warned and write your own code :)
91
+
92
+ And that's it! All your models that have `has_attached_file :avatar` will copy
93
+ the file specified by s3_key to the path expected by paperclip.
82
94
 
83
95
  ## Options for form helper
96
+
97
+ All these options are still used in code, but the callbacks options doesn't have
98
+ any effect. I will polish it when I have some tests written.
99
+
84
100
  * `callback_url:` No default. The url that is POST'd to after file is uploaded to S3. If you don't specify this option, no callback to the server will be made after the file has uploaded to S3.
85
101
  * `callback_method:` Defaults to `POST`. Use PUT and remove the multiple option from your file field to update a model.
86
102
  * `callback_param:` Defaults to `file`. Parameter key for the POST to `callback_url` the value will be the full s3 url of the file. If for example this is set to "model[image_url]" then the data posted would be `model[image_url] : http://bucketname.s3.amazonws.com/filename.ext`
@@ -93,158 +109,10 @@ Optionally, you can also place this template in the same view for the progress b
93
109
  * `data:` Optional html data attribute hash.
94
110
  * `bucket:` Optional (defaults to bucket used in config).
95
111
 
96
- ### Example with all options
97
- ```ruby
98
- <%= s3_uploader_form callback_url: model_url,
99
- callback_method: "POST",
100
- callback_param: "model[image_url]",
101
- key: "files/{timestamp}-{unique_id}-#{SecureRandom.hex}/${filename}",
102
- key_starts_with: "files/",
103
- acl: "public-read",
104
- max_file_size: 50.megabytes,
105
- id: "s3-uploader",
106
- class: "upload-form",
107
- data: {:key => :val} do %>
108
- <%= file_field_tag :file, multiple: true %>
109
- <% end %>
110
- ```
111
-
112
- ### Example to persist the S3 url in your rails app
113
- It is recommended that you persist the url that is sent via the POST request (to the url given to the `callback_url` option and as the key given in the `callback_param` option).
114
-
115
- One way to do this is to make sure you have `resources model` in your routes file, and add a `s3_url` (or something similar) attribute to your model. Then make sure you have the create action in your controller for that model that saves the url from the callback_param.
116
-
117
- You could then have your create action render a javascript file like this:
118
- **create.js.erb**
119
- ```ruby
120
- <% if @model.new_record? %>
121
- alert("Failed to upload model: <%= j @model.errors.full_messages.join(', ').html_safe %>");
122
- <% else %>
123
- $("#container").append("<%= j render(@model) %>");
124
- <% end %>
125
- ```
126
- So that javascript code would be executed after the model instance is created, without a page refresh. See [@rbates's gallery-jquery-fileupload](https://github.com/railscasts/383-uploading-to-amazon-s3/tree/master/gallery-jquery-fileupload)) for an example of that method.
127
-
128
- Note: the POST request to the rails app also includes the following parameters `filesize`, `filetype`, `filename` and `filepath`.
129
-
130
- ### Advanced Customizations
131
- Feel free to override the styling for the progress bars in s3-upnow_progress_bars.css, look at the source for inspiration.
132
-
133
- Also feel free to write your own js to interface with jquery-file-upload. You might want to do this to do custom validations on the files before it is sent to S3 for example.
134
- To do this remove `s3-upnow` from your application.js and include the necessary jquery-file-upload scripts in your asset pipeline (they are included in this gem automatically):
135
- ```cofeescript
136
- #= require jquery-fileupload/basic
137
- #= require jquery-fileupload/vendor/tmpl
138
- ```
139
- Use the javascript in `s3-upnow` as a guide.
140
-
141
-
142
- ## Options for S3Upload jQuery Plugin
143
-
144
- * `path:` manual path for the files on your s3 bucket. Example: `path/to/my/files/on/s3`
145
- Note: Your path MUST start with the option you put in your form builder for `key_starts_with`, or else you will get S3 permission errors. The file path in your s3 bucket will be `path + key`.
146
- * `additional_data:` You can send additional data to your rails app in the persistence POST request. This would be accessible in your params hash as `params[:key][:value]`
147
- Example: `{key: value}`
148
- * `remove_completed_progress_bar:` By default, the progress bar will be removed once the file has been successfully uploaded. You can set this to `false` if you want to keep the progress bar.
149
- * `remove_failed_progress_bar:` By default, the progress bar will not be removed when uploads fail. You can set this to `true` if you want to remove the progress bar.
150
- * `before_add:` Callback function that executes before a file is added to the queue. It is passed file object and expects `true` or `false` to be returned. This could be useful if you would like to validate the filenames of files to be uploaded for example. If true is returned file will be uploaded as normal, false will cancel the upload.
151
- * `progress_bar_target:` The jQuery selector for the element where you want the progress bars to be appended to. Default is the form element.
152
- * `click_submit_target:` The jQuery selector for the element you wish to add a click handler to do the submitting instead of submiting on file open.
153
-
154
- ### Example with all options
155
- ```coffeescript
156
- jQuery ->
157
- $("#myS3Uploader").S3Uploader
158
- path: 'path/to/my/files/on/s3'
159
- additional_data: {key: 'value'}
160
- remove_completed_progress_bar: false
161
- before_add: myCallBackFunction # must return true or false if set
162
- progress_bar_target: $('.js-progress-bars')
163
- click_submit_target: $('.submit-target')
164
- ```
165
- ### Example with single file upload bar without script template
166
-
167
- This demonstrates how to use progress_bar_target and allow_multiple_files (only works with false option - single file) to show only one progress bar without script template.
168
-
169
- ```coffeescript
170
- jQuery ->
171
- $("#myS3Uploader").S3Uploader
172
- progress_bar_target: $('.js-progress-bars')
173
- allow_multiple_files: false
174
- ```
175
-
176
- Target for progress bar
177
-
178
- ```html
179
- <div class="upload js-progress-bars">
180
- <div class="progress">
181
- <div class="bar"> </div>
182
- </div>
183
- </div>
184
- ```
185
-
186
-
187
-
188
-
189
- ### Public methods
190
- You can change the settings on your form later on by accessing the jQuery instance:
191
-
192
- ```coffeescript
193
- jQuery ->
194
- v = $("#myS3Uploader").S3Uploader()
195
- ...
196
- v.path("new/path/") #only works when the key_starts_with option is blank. Not recommended.
197
- v.additional_data("newdata")
198
- ```
199
-
200
- ### Javascript Events Hooks
201
-
202
- #### First upload started
203
- `s3_uploads_start` is fired once when any batch of uploads is starting.
204
- ```coffeescript
205
- $('#myS3Uploader').bind 's3_uploads_start', (e) ->
206
- alert("Uploads have started")
207
- ```
208
-
209
- #### Successfull upload
210
- When a file has been successfully uploaded to S3, the `s3_upload_complete` is triggered on the form. A `content` object is passed along with the following attributes :
211
-
212
- * `url` The full URL to the uploaded file on S3.
213
- * `filename` The original name of the uploaded file.
214
- * `filepath` The path to the file (without the filename or domain)
215
- * `filesize` The size of the uploaded file.
216
- * `filetype` The type of the uploaded file.
217
-
218
- This hook could be used for example to fill a form hidden field with the returned S3 url :
219
- ```coffeescript
220
- $('#myS3Uploader').bind "s3_upload_complete", (e, content) ->
221
- $('#someHiddenField').val(content.url)
222
- ```
223
-
224
- #### Failed upload
225
- When an error occured during the transferm the `s3_upload_failed` is triggered on the form with the same `content` object is passed for the successful upload with the addition of the `error_thrown` attribute. The most basic way to handle this error would be to display an alert message to the user in case the upload fails :
226
- ```coffeescript
227
- $('#myS3Uploader').bind "s3_upload_failed", (e, content) ->
228
- alert("#{content.filename} failed to upload : #{content.error_thrown}")
229
- ```
230
-
231
- #### All uploads completed
232
- When all uploads finish in a batch an `s3_uploads_complete` event will be triggered on `document`, so you could do something like:
233
- ```coffeescript
234
- $(document).bind 's3_uploads_complete', ->
235
- alert("All Uploads completed")
236
- ```
237
-
238
- #### Rails AJAX Callbacks
239
-
240
- In addition, the regular rails ajax callbacks will trigger on the form with regards to the POST to the server.
112
+ ## Cleaning old uploads on S3
241
113
 
242
- ```coffeescript
243
- $('#myS3Uploader').bind "ajax:success", (e, data) ->
244
- alert("server was notified of new file on S3; responded with '#{data}")
245
- ```
114
+ PS.: I don't test if it's already working, but I intend to do it soon.
246
115
 
247
- ## Cleaning old uploads on S3
248
116
  You may be processing the files upon upload and reuploading them to another
249
117
  bucket or directory. If so you can remove the originali files by running a
250
118
  rake task.
@@ -262,7 +130,9 @@ Then, run the rake task to delete uploads older than 2 days:
262
130
  $
263
131
  ```
264
132
 
265
- Optionally customize the prefix used for cleaning (default is `uploads/#{2.days.ago.strftime('%Y%m%d')}`):
133
+ Optionally customize the prefix used for cleaning (default is
134
+ `uploads/#{2.days.ago.strftime('%Y%m%d')}`):
135
+
266
136
  **config/initalizers/s3-upnow.rb**
267
137
  ```ruby
268
138
  S3UpNow.config do |c|
@@ -271,34 +141,21 @@ S3UpNow.config do |c|
271
141
  end
272
142
  ```
273
143
 
274
- Alternately, if you'd prefer for S3 to delete your old uploads automatically, you can do
275
- so by setting your bucket's
276
- [Lifecycle Configuration](http://docs.aws.amazon.com/AmazonS3/latest/UG/LifecycleConfiguration.html).
277
-
278
- ## A note on IE support
279
- IE file uploads are working but with a couple caveats.
280
-
281
- * The before_add callback doesn't work.
282
- * The progress bar doesn't work on IE.
283
-
284
- But IE should still upload your files fine.
285
-
144
+ Alternately, if you'd prefer for S3 to delete your old uploads automatically,
145
+ you can do so by setting your bucket's [Lifecycle Configuration](http://docs.aws.amazon.com/AmazonS3/latest/UG/LifecycleConfiguration.html).
286
146
 
287
147
  ## Contributing / TODO
288
- This is just a simple gem that only really provides some javascript and a form helper.
289
- This gem could go all sorts of ways based on what people want and how people contribute.
148
+ This is just a simple gem that only really provides some javascript and a form
149
+ helper. This gem could go all sorts of ways based on what people want and how
150
+ people contribute.
151
+
290
152
  Ideas:
291
153
  * More specs!
292
154
  * More options to control file types, ability to batch upload.
293
- * More convention over configuration on rails side
294
- * Create generators.
295
- * Model methods.
296
- * Model method to delete files from s3
155
+ * More convention over configuration on frontend side
297
156
 
298
157
 
299
158
  ## Credit
300
- This gem is basically a small wrapper around code that [Ryan Bates](http://github.com/rbates) wrote for [Railscast#383](http://railscasts.com/episodes/383-uploading-to-amazon-s3). Most of the code in this gem was extracted from [gallery-jquery-fileupload](https://github.com/railscasts/383-uploading-to-amazon-s3/tree/master/gallery-jquery-fileupload).
301
-
302
- Thank you Ryan Bates!
303
-
304
- This code also uses the excellecnt [jQuery-File-Upload](https://github.com/blueimp/jQuery-File-Upload), which is included in this gem by its rails counterpart [jquery-fileupload-rails](https://github.com/tors/jquery-fileupload-rails)
159
+ This gem is a hybrid of [s3_direct_upload](https://github.com/waynehoover/s3_direct_upload)
160
+ and [refile](https://github.com/elabs/refile). Maybe it have more personality in
161
+ the future.
@@ -3,6 +3,10 @@ $(document).on 'change', (e) ->
3
3
  if (input.prop('tagName') == "INPUT" && input.prop('type') == "file" && input.data('upnow'))
4
4
  return if (!input.prop('files'))
5
5
  file = input.prop('files')[0]
6
+ max_file_size = Number(input.attr('max_file_size') || <%= 500.megabytes %>)
7
+ if Number(file.size) > max_file_size
8
+ alert("<%= I18n.t('s3_upnow.max_file_size') %>: #{max_file_size/1024/1024}mb")
9
+ return
6
10
  file.unique_id = Math.random().toString(36).substr(2,16)
7
11
 
8
12
  dispatchEvent = (name, detail) ->
@@ -10,7 +10,8 @@ module S3UpNow
10
10
  end
11
11
 
12
12
  def s3_upnow_destination_bucket(name)
13
- s3_upnow_attachment(name).options[:bucket].call
13
+ attachment = s3_upnow_attachment(name)
14
+ attachment.options[:s3_credentials].try(:[], :bucket) || attachment.options[:bucket].call
14
15
  end
15
16
 
16
17
  def s3_upnow_destination_path(name)
@@ -26,17 +27,21 @@ module S3UpNow
26
27
 
27
28
  module ClassMethods
28
29
  def has_attached_file(name, options = {})
29
- puts "here"
30
30
  self.class_eval do
31
31
  attr_accessor "#{name}_s3_key"
32
32
 
33
- before_validation "s3_upnow_copy_metadata_from_#{name}".to_sym, unless: "#{name}_s3_key.blank?"
34
- after_save "s3_upnow_copy_file_from_#{name}".to_sym, unless: "#{name}_s3_key.blank?"
33
+ before_validation "s3_upnow_copy_metadata_from_#{name}".to_sym, unless: -> { send("#{name}_s3_key").blank? }
34
+ after_save "s3_upnow_copy_file_from_#{name}".to_sym, unless: -> { send("#{name}_s3_key").blank? }
35
35
 
36
36
  private
37
37
 
38
+ def s3_upnow_client
39
+ endpoint = "#{S3UpNow.config.region ? S3UpNow.config.region : 's3'}.amazonaws.com"
40
+ AWS::S3.new(s3_endpoint: endpoint)
41
+ end
42
+
38
43
  define_method "s3_upnow_copy_metadata_from_#{name}" do
39
- s3 = AWS::S3.new
44
+ s3 = s3_upnow_client
40
45
  s3_head = s3.buckets[S3UpNow.config.bucket].objects[instance_variable_get("@#{name}_s3_key")].head
41
46
 
42
47
  s3_upnow_attachment(name).clear
@@ -47,15 +52,19 @@ module S3UpNow
47
52
  end
48
53
 
49
54
  define_method "s3_upnow_copy_file_from_#{name}" do
50
- s3 = AWS::S3.new
55
+ s3 = s3_upnow_client
51
56
  orig_bucket = s3.buckets[S3UpNow.config.bucket]
52
57
  orig_object = orig_bucket.objects[instance_variable_get("@#{name}_s3_key")]
53
58
  dest_bucket = s3.buckets[s3_upnow_destination_bucket(name)]
54
59
  dest_object = dest_bucket.objects[s3_upnow_destination_path(name)]
55
60
  dest_object.copy_from(orig_object, acl: s3_upnow_destination_permissions(name))
61
+ if s3_upnow_attachment(name).styles.present?
62
+ remove_instance_variable("@#{name}_s3_key")
63
+ s3_upnow_attachment(name).reprocess!
64
+ end
56
65
  end
57
66
  end
58
67
  super(name, options)
59
68
  end
60
69
  end
61
- end
70
+ end
@@ -1,3 +1,3 @@
1
1
  module S3UpNow
2
- VERSION = "0.2.0"
2
+ VERSION = "0.3.0"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: s3-upnow
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Carlos Eduardo Rodrigues Diógenes
8
- autorequire:
8
+ autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2015-01-03 00:00:00.000000000 Z
11
+ date: 2020-12-18 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -75,7 +75,7 @@ extra_rdoc_files: []
75
75
  files:
76
76
  - LICENSE
77
77
  - README.md
78
- - app/assets/javascripts/s3-upnow.js.coffee
78
+ - app/assets/javascripts/s3-upnow.coffee.erb
79
79
  - app/assets/stylesheets/s3-upnow-progress-bar.css.scss
80
80
  - lib/s3-upnow.rb
81
81
  - lib/s3-upnow/config_aws.rb
@@ -89,7 +89,7 @@ files:
89
89
  homepage: ''
90
90
  licenses: []
91
91
  metadata: {}
92
- post_install_message:
92
+ post_install_message:
93
93
  rdoc_options: []
94
94
  require_paths:
95
95
  - lib
@@ -104,9 +104,9 @@ required_rubygems_version: !ruby/object:Gem::Requirement
104
104
  - !ruby/object:Gem::Version
105
105
  version: '0'
106
106
  requirements: []
107
- rubyforge_project:
108
- rubygems_version: 2.4.2
109
- signing_key:
107
+ rubyforge_project:
108
+ rubygems_version: 2.7.6.2
109
+ signing_key:
110
110
  specification_version: 4
111
111
  summary: Gives a form helper for Rails which allows direct uploads to s3. Based on
112
112
  RailsCast#383