Skip to content

Instantly share code, notes, and snippets.

@syabro
Created September 1, 2014 12:11
Show Gist options
  • Save syabro/b8c296f37b9eb20cf612 to your computer and use it in GitHub Desktop.
Save syabro/b8c296f37b9eb20cf612 to your computer and use it in GitHub Desktop.
Plupload django directive
.directive('uploadFile', ($http, $timeout, $staticUrl, $cookies, $log, $attachedFileApiUrl)->
return {
restrict: 'A'
template: (tElement, tAttrs)->
return tElement[0].innerHTML
scope:
ngModel: '='
compile: ($element, $attrs) ->
return (scope, $element, $attrs)->
uploader = null;
attachments_dict = {}
scope.image_url = ''
browse_button_id = "browse_button_id-#{ Math.round(Math.random()*100000000) }"
$browse_button = $element.find($attrs.browseButton)
$browse_button.attr('id', browse_button_id);
scope.initUploader = ->
if uploader
return false;
$timeout ()->
params =
runtimes : 'html5,flash'
browse_button : browse_button_id
max_file_size : '1gb'
url : $attachedFileApiUrl
flash_swf_url: $staticUrl + 'libs/plupload-1.5.5/plupload.flash.swf',
multi_selection: true
file_data_name: 'file'
headers:
'Accept': 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'
'X-Requested-With': 'XMLHttpRequest'
"X-CSRFToken": $cookies.csrftoken
multipart_params: {
model: $attrs['model']
}
if $attrs['browseContainer']
params['container'] = $attrs['browseContainer']
uploader = new plupload.Uploader(params)
uploader.bind('FilesAdded', (uploader, files) ->
$timeout(->
uploader.start()
, 500)
)
uploader.bind 'UploadProgress', (up, file) ->
if attachments_dict[file.uuid]
attachments_dict[file.uuid].loaded = file.loaded
attachments_dict[file.uuid].loadedPercents = Math.round((file.loaded / file.size) * 100)
scope.$apply()
uploader.bind 'Error', (uploader, error) ->
if error && error.file
attachments_dict[error.file.uuid].uploaded = true
scope.$apply()
$log.error('Uploader Error', error)
uploader.bind 'FileUploaded', (uploader, file, response) ->
data = JSON.parse(response.response)
scope.ngModel = data.id
scope.url = data.url
scope.filename = data.filename
scope.$apply()
uploader.init()
if $attrs['initWhenTrue']?
scope.$watch($attrs['initWhenTrue'], (val, oldVal)->
if val && !oldVal
setTimeout(()->
scope.initUploader()
)
else if val && !uploader
setTimeout(()->
scope.initUploader()
,500)
else if val
setTimeout(()->
scope.initUploader()
,500)
)
else
setTimeout(->
scope.initUploader()
)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment