Skip to content

Commit

Permalink
Merge pull request #16 from pomartel/trigger_fail_event
Browse files Browse the repository at this point in the history
Trigger fail event
  • Loading branch information
Wayne committed Nov 10, 2012
2 parents fc9707d + aa35507 commit 64801c9
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 62 deletions.
97 changes: 53 additions & 44 deletions README.md
Expand Up @@ -22,7 +22,7 @@ end
```

Make sure your AWS S3 CORS settings for your bucket look something like this:
```
```xml
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>http://0.0.0.0:3000</AllowedOrigin>
Expand Down Expand Up @@ -62,7 +62,7 @@ jQuery ->
$("#myS3Uploader").S3Uploader()
```

Also place this template in the same view for the progress bars:
Optionally, you can also place this template in the same view for the progress bars:
```js+erb
<script id="template-upload" type="text/x-tmpl">
<div class="upload">
Expand All @@ -73,20 +73,14 @@ Also place this template in the same view for the progress bars:
```

## Options for form helper
`post:` -> url in which is POST'd to after file is uploaded to S3. Example: model_url

`as:` -> parameter value for the POST in which the key will be the URL of the file on S3. 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`

`key:` -> key on s3. defaults to `"uploads/#{SecureRandom.hex}/${filename}"`. needs to be at least `"${filename}"`.

`acl:` -> acl for files uploaded to s3, defaults to "public-read"

`max_file_size:` -> maximum file size, defaults to 500.megabytes

`id:` -> html id for the form, its recommended that you give the form an id so you can reference with the jQuery plugin.

`class:` -> optional html class for the form.

* `post:` url in which 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.
* `as:` parameter value for the POST in which the key will be the URL of the file on S3. 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`
* `key:` key on s3. defaults to `"uploads/#{SecureRandom.hex}/${filename}"`. needs to be at least `"${filename}"`.
* `acl:` acl for files uploaded to s3, defaults to "public-read"
* `max_file_size:` maximum file size, defaults to 500.megabytes
* `id:` html id for the form, its recommended that you give the form an id so you can reference with the jQuery plugin.
* `class:` optional html class for the form.
* `data:` Optional html data

### Persisting the S3 url
It is recommended that you persist the image_url that is sent back from the POST request (to the url given to the `post` option and as the key given in the `as` option). So to access your files later.
Expand Down Expand Up @@ -120,50 +114,66 @@ Use the javascript in `s3_direct_upload` as a guide.
## Options for S3Upload jQuery Plugin
`path` -> manual path for the files on your s3 bucket. Example: `path/to/my/files/on/s3`

Note: the file path in your s3 bucket will effectively be `path + key`.

`additional_data` -> You can send additional data to your rails app in the persistence POST request. Example: `{key: value}`

This would be accessable in your params hash as `params[:key][:value]`
* `path:` manual path for the files on your s3 bucket. Example: `path/to/my/files/on/s3`
Note: the file path in your s3 bucket will effectively be `path + key`.
* `additional_data:` You can send additional data to your rails app in the persistence POST request. This would be accessable in your params hash as `params[:key][:value]`
Example: `{key: value}`
* `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.
* `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.
`before_add` -> Callback function that executes before a file is added to the que. 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.
### Example with all options.
```coffeescript
jQuery ->
$("#myS3Uploader").S3Uploader
path: 'path/to/my/files/on/s3'
additional_data: {key: 'value'}
remove_completed_progress_bar: false
before_add: myCallBackFunction() # must return true or false if set
```

### Public methods
You can change the settings on your form later on by accessing the jQuery instance:

```cofeescript
```coffeescript
jQuery ->
v = $("#myS3Uploader").S3Uploader()
...
v.path("new/path/")
v.additional_data("newdata")
```

### Global Event Hooks
### Javascript Events Hooks

When all uploads finish in a batch an `s3_uploads_complete` event will be triggered on `document`, so you could do something like:
```javascript
$(document).bind('s3_uploads_complete', function(){
...
alert("All Uploads completed")
});
````
### Example with all options.
```cofeescript
jQuery ->
$("#myS3Uploader").S3Uploader
path: 'path/to/my/files/on/s3'
additional_data: {key: 'value'}
before_add: myCallBackFunction() # must return true or false if set
#### Successfull upload
When a file has been successfully to S3, the `s3_upload_complete` is triggered on the form. A `content` object is passed along with the following attributes :

* `url` The full URL to the uploaded file on S3.
* `filename` The original name of the uploaded file.
* `filepath` The path to the file (without the filename or domain)
* `filesize` The size of the uploaded file.
* `filetype` The type of the uploaded file.

This hook could be used for example to fill a form hidden field with the returned S3 url :
```coffeescript
$('#myS3Uploader').bind "s3_upload_complete", (e, content) ->
$('#someHiddenField').val(content.url)
```

#### Failed upload
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 :
```coffeescript
$('#myS3Uploader').bind "s3_upload_failed", (e, content) ->
alert("#{content.filename} failed to upload : #{content.error_thrown}")
```

#### All uploads completed
When all uploads finish in a batch an `s3_uploads_complete` event will be triggered on `document`, so you could do something like:
```coffeescript
$(document).bind 's3_uploads_complete', ->
alert("All Uploads completed")
```

## Contributing / TODO

This is just a simple gem that only really provides some javascript and a form helper.
This gem could go all sorts of ways based on what people want and how people contribute.
Ideas:
Expand All @@ -176,7 +186,6 @@ Ideas:


## Credit

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).

Thank you Ryan Bates!
Expand Down
33 changes: 16 additions & 17 deletions app/assets/javascripts/s3_direct_upload.js.coffee
Expand Up @@ -40,20 +40,7 @@ $.fn.S3Uploader = (options) ->
data.context.find('.bar').css('width', progress + '%')

done: (e, data) ->
file = data.files[0]
domain = $uploadForm.attr('action')
path = settings.path + $uploadForm.find('input[name=key]').val().replace('/${filename}', '')

content = {}
content.url = domain + path + '/' + file.name
content.filename = file.name
content.filepath = path
if settings.additional_data
content = $.extend content, settings.additional_data
if 'size' of file
content.filesize = file.size
if 'type' of file
content.filetype = file.type
content = build_content_object $uploadForm, data.files[0]

to = $uploadForm.data('post')
if to
Expand All @@ -68,9 +55,9 @@ $.fn.S3Uploader = (options) ->
$(document).trigger("s3_uploads_complete")

fail: (e, data) ->
alert("#{data.files[0].name} failed to upload.")
console.log("Upload failed:")
console.log(data)
content = build_content_object $uploadForm, data.files[0]
content.error_thrown = data.errorThrown
$uploadForm.trigger("s3_upload_failed", [content])

formData: (form) ->
data = form.serializeArray()
Expand All @@ -85,6 +72,18 @@ $.fn.S3Uploader = (options) ->

data

build_content_object = ($uploadForm, file) ->
domain = $uploadForm.attr('action')
path = settings.path + $uploadForm.find('input[name=key]').val().replace('/${filename}', '')
content = {}
content.url = domain + path + '/' + file.name
content.filename = file.name
content.filepath = path
content.filesize = file.size if 'size' of file
content.filetype = file.type if 'type' of file
content = $.extend content, settings.additional_data if settings.additional_data
content

#public methods
@initialize = ->
setUploadForm()
Expand Down
2 changes: 1 addition & 1 deletion lib/s3_direct_upload/form_helper.rb
Expand Up @@ -33,7 +33,7 @@ def form_options
data: {
post: @options[:post],
as: @options[:as]
}
}.reverse_merge(@options[:data] || {})
}
end

Expand Down

0 comments on commit 64801c9

Please sign in to comment.