Skip to content

Instantly share code, notes, and snippets.

@fastcodecoq
Last active December 22, 2015 23:19
Show Gist options
  • Save fastcodecoq/6545827 to your computer and use it in GitHub Desktop.
Save fastcodecoq/6545827 to your computer and use it in GitHub Desktop.
$.ajax uploader
/*
USO
var opts = {
bar_text : "#progress", // elemento donde se colocará el porcentaje de carga
load_bar : "#upload_bar", // la barra de progreso (la que va aumentando) ______ ...
allowed_files_ext : new Array("mp3", "ogg"), //extensiones permitidas (siempre debes validar del lado servidor)
upload_url : "/upload", // archivo a donde se carga (uploads.php)
size_limit : "30000000", // tamaño máximo de cada archivo por bytes
progress_action : function(){}, // que hará el code cada que halla progreso retorna un objeto con el % progreso actual
upload_success: function(){}, // que hará el code cuando halla cargado los archivos
upload_error : function(){}, // que hará el code en caso de error
drag_drop : true
}
$("formulario").upload(opts);
Copyrights @gomosoft
LICENSE GPL v3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function(){
var _this;
var data = {
bar_text : "#progress",
load_bar : "#upload_bar",
allowed_files_ext : new Array("mp3", "ogg"),
upload_url : "/upload",
size_limit : "30000000",
progress_action : function(percent){
if( percent > 5 ){
data.load_bar.css({
width : percent + "%"
}).find(data.bar_text).text(percent + "%");
}
if(percent === 100){
data.load_bar.fadeOut( function(){
$(this).css({width:"0px"}).removeClass("bordered");
$(this).find(data.bar_text).text("0%");
});
data.load_bar.removeClass("loading");
}
console.log( percent );
},
upload_success : function(r){
console.log(r);
if(r.success)
if(r.success == 0 )
alert(r.rs.msg);
},
upload_error : function(error){
console.log(error);
alert(error.responseText);
},
drag_drop : function ( ) {
var holder = document.querySelector(_this);
holder.ondragover = function () {
e.preventDefault();
this.className = 'span5 hover';
$(holder).find("span.msg").html("Drop Files <b><em>HERE</em></b>");
};
holder.ondragend = function () {
this.className = 'span5';
$(holder).find("span.ms").html("Drag files <b><em>HERE</em></b>");
};
holder.ondragleave = function () {
this.className = 'span5';
$(holder).find("span.msg").html("Drag files <b><em>HERE</em></b>");
};
holder.ondrop = function (e) {
e.preventDefault();
e.stopPropagation();
this.className = 'span5';
console.log(e);
holder.find("span.msg").html("Drag files <b><em>HERE</em></b>");
procFiles(e.dataTransfer.files);
return false;
};
}
};
var drag_drop ;
$.fn.upload = function(vars){
if(vars instanceof Object)
$.extend(data, vars );
_this = $(this);
data.load_bar = $(data.load_bar);
if(data.drag_drop)
drag_drop();
upController();
console.log("Upload iniciado");
}
var drag_drop = function (){
var body = document.querySelector("body");
var dropbox = document.querySelector("#dropbox");
body.ondragover = function(){
$(dropbox).show("fast");
$(dropbox).addClass("dragdrop");
return false;
}
body.ondrop = function(e){
e.preventDefault();
return false;
}
dropbox.ondrop = function(e){
e.preventDefault();
procFiles(e.dataTransfer.files);
$(dropbox).removeClass("dragdrop").fadeOut();
return false;
}
dropbox.ondragover = function(e){
$(dropbox).show("fast");
$(dropbox).addClass("dragdrop");
return false;
}
dropbox.ondragleave = function(){
$(dropbox).hide();
$(dropbox).removeClass("dragdrop");
return false;
}
}
var upController = function (){
_this.find("input[type='file']:first").live('change', function(){
var files = this.files;
procFiles(files);
});
}
var procFiles = function (files){
if(files.length == 0)
return;
var reader, file, files,filesData,files_ = new Array();
var exts = data.allowed_files_ext;
if(window.FormData){
filesData = new FormData();
}
for(i=0; i<files.length;i++){
var ext = files[i].name.toString().split(".");
ext = ext[ ext.length - 1 ];
ext = ext.toLowerCase();
_exts = data.allowed_files_ext.join(" ");
if(! inArray(ext,exts) )
if(files.length > 1)
{
var preg = confirm("Solo puedes cargar archivos con las extensiones " + _exts + ", Deseas omitir este archivo y continuar con la carga?");
if(!preg)
return;
}
else{
alert("Solo puedes cargar archivos con las extensiones " + _exts);
return;
}
if(files[i].size > data.size_limit)
{
alert("Desafortunadamente tu archivo excede el peso máximo permitido por archivo, 8MB");
return;
}
else
filesData.append(i,files[i]);
}
console.log(filesData)
sendFiles(filesData);
}
var sendFiles = function ( files ){
var min = 10;
data.load_bar.addClass("bordered");
data.load_bar.show();
$.ajax({
url : data.upload_url,
type : 'POST',
data : files,
dataType : false,
processData : false,
contentType : false,
statusCode : {
"404" : function(){ alert("pagina no encontrada"); }
},
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
var percent = parseFloat(Math.round( (percentComplete*100)));
data.progress_action(percent);
}
}, false);
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
}
}, false);
return xhr;
},
success : data.upload_success,
error : data.upload_error
});
}
})(jQuery);
/* Happy Coding */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment