Created
January 16, 2015 16:53
-
-
Save AmazingDreams/b243a2112dea2da1c480 to your computer and use it in GitHub Desktop.
HTML5 uploader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function() { | |
$(".js-uploader").each(function() { | |
var $form = $(this.form); | |
var $display = $($(this).attr('data-filedisplay')); | |
var targetURL = $(this).attr('data-targeturl'); | |
var template = $($(this).attr('data-template')).html(); | |
$(this).on('change', function() { | |
var files = this.files; | |
$(files).each(function() { | |
var $obj = $(template); | |
var $progress = $obj.find("[role='progressbar']"); | |
var img = $obj.find('img'); | |
$display.append($obj); | |
var reader = new FileReader(); | |
var formData = new FormData(); | |
reader.onload = function(e) { | |
$(img).attr('src', e.target.result); | |
}; | |
formData.append('file', this); | |
reader.readAsDataURL(this); | |
$.ajax({ | |
url : targetURL, | |
type : 'POST', | |
data : formData, | |
processData : false, | |
contentType : false, | |
dataType : 'json', | |
xhr : function() { | |
var customXHR = $.ajaxSettings.xhr(); | |
if(customXHR.upload) { | |
customXHR.upload.addEventListener('progress', function(e) { | |
if ( ! e.lengthComputable) return; | |
var percentage = Math.round((e.loaded * 100) / e.total); | |
$progress.attr('aria-valuenow', percentage); | |
$progress.css('width', percentage +'%'); | |
$progress.html(percentage +'%'); | |
}); | |
} | |
return customXHR; | |
}, | |
success : function(result) { | |
var html = $obj.html().replace(/{id}/g, result.id); | |
$obj.html(html); | |
$progress.html('Done!'); | |
} | |
}); | |
}); | |
}); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment