Skip to content

Instantly share code, notes, and snippets.

@mmplisskin
Forked from ychaker/upload_doc.coffee
Created May 10, 2017 02:05
Show Gist options
  • Save mmplisskin/54b6df29b341abb3f4debb61b7bc0e9b to your computer and use it in GitHub Desktop.
Save mmplisskin/54b6df29b341abb3f4debb61b7bc0e9b to your computer and use it in GitHub Desktop.
Rails + Refile + Dropzone (6)
$(document).ready ->
Dropzone.autoDiscover = false
$(document).on 'shown.bs.modal', '.upload-modal', ->
modal = this
previewTemplate = $('#' + modal.id + ' .dz-file-preview')[0].innerHTML
# Make sure to only initialize the dropzone once.
if ( $('#' + modal.id + ' .dropzone:not(.dz-attached)').length )
dropzone = new Dropzone('#' + modal.id + ' .dropzone', {
maxFilesize: 20, # Set the maximum file size to 20 MB
maxFiles: 1,
uploadMultiple: false,
previewTemplate: previewTemplate,
paramName: 'doc[file]',
clickable: '[data-dz-clickable]',
autoProcessQueue: false,
maxfilesexceeded: (file) ->
this.removeAllFiles()
this.addFile(file)
success: (file, response) ->
this.removeAllFiles()
resume_after_doc_upload($(modal))
$(modal).modal('hide')
message = '<div class="alert alert-success alert-dismissable fade in">
<button
type="button"
class="close"
data-dismiss="alert"
aria-hidden="true"
>&times;</button>
Doc uploaded successfully.
</div>'
$('#alerts').html(message)
if (response.updated)
$.get '/docs/' + response.id + '/reload.js'
else
$.get '/docs/reload.js'
})
dropzone.on 'totaluploadprogress', (progress) ->
document.querySelector('[data-dz-uploadprogress]').style.width = progress + '%'
$('button[type=submit]', modal).click (event) ->
if ( dropzone.getQueuedFiles().length )
event.preventDefault()
wait_for_doc_upload($(modal))
dropzone.processQueue()
else
return true
$('#' + modal.id + ' .dropzone').addClass('dz-attached')
wait_for_doc_upload = (form) ->
button = form.find('button[type=submit]')
button.attr('disabled', true)
button.html('<i class="fa fa-spinner fa-spin"></i>')
resume_after_doc_upload = (form) ->
if( !form.find('button.uploading').length )
button = form.find('button[type=submit]')
button.removeAttr('disabled')
button.html('Upload')
$(document).on 'upload:start', 'form#new_doc', ->
wait_for_doc_upload($(this))
$(document).on 'upload:start', 'form[id^=edit_doc]', ->
wait_for_doc_upload($(this))
$(document).on 'upload:complete', 'form#new_doc', ->
resume_after_doc_upload($(this))
$(document).on 'upload:complete', 'form[id^=edit_doc]', ->
resume_after_doc_upload($(this))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment