Skip to content

Instantly share code, notes, and snippets.

@melito
Created July 11, 2011 23:46
Show Gist options
  • Save melito/1077071 to your computer and use it in GitHub Desktop.
Save melito/1077071 to your computer and use it in GitHub Desktop.
Usage
$("#media_items").html5Uploader({
url: "<%= assets_path %>",
method: 'POST',
params: {
authenticity_token: "<%= form_authenticity_token %>"
}
});
class HTML5Uploader
constructor:(obj, options) ->
@method = options['method'] ||= "POST"
@url = options['url'] ||= "/"
@params = options['params']
_.bindAll(this, 'dragEnter', 'dragOver', 'drop')
$(obj).bind('dragenter', this.dragEnter)
$(obj).bind('dragover', this.dragOver)
$(obj).bind('drop', this.drop)
dragEnter:(event) ->
event.stopPropagation()
event.preventDefault()
return false
dragOver:(event) ->
event.stopPropagation()
event.preventDefault()
return false
drop:(event) ->
event.stopPropagation()
event.preventDefault()
dataTransfer = event.originalEvent.dataTransfer
self = this
# If we have some files in the drop event
if dataTransfer.files.length > 0
# Iterate over each of them and send them to the server
$.each dataTransfer.files, (i, file) ->
# Build an ajax request
xhr = new XMLHttpRequest()
upload = xhr.upload
# Build a form object for building the request
fd = new FormData()
if self.params != undefined
_.each _.keys(self.params), (key) ->
fd.append(key, self.params[key])
# Append the file to the asset object in the request
fd.append('asset', file)
# Fire it up
xhr.open(self.method, self.url, true)
xhr.setRequestHeader('X-Filename', file.fileName)
xhr.send(fd)
return false
$.fn.html5Uploader = (method) ->
return new HTML5Uploader(this, method)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment