Skip to content

Instantly share code, notes, and snippets.

@cdsaenz
Created November 3, 2023 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdsaenz/cc97dd30916657931ef5cb7e92ef7078 to your computer and use it in GitHub Desktop.
Save cdsaenz/cc97dd30916657931ef5cb7e92ef7078 to your computer and use it in GitHub Desktop.
Uploader Handler
/* generic alert on error requires jquery.confirm */
function alert_error(errorMsg) {
$.confirm({
icon: 'fas fa-exclamation-triangle',
type: 'red',
title: 'Error!',
buttons: {'Close': function(){}},
content: errorMsg,
});
}
$(document).ready(function(){
// File upload via Ajax
$("#uploadForm").on('submit', function(e){
e.preventDefault();
let files = document.getElementById("fileInput").files;
if (files.length == 0) {
alert_error("<i>No file</i> was selected to upload");
return false;
}
$('.progress').removeClass('d-none');
$.ajax({
xhr: function() {
// the key: showing progress until the finish
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor( (evt.loaded / evt.total) * 100);
$(".progress-bar").width(percentComplete + '%');
$(".progress-bar").html(percentComplete+'%');
}
}, false);
return xhr;
},
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$(".progress-bar").width('0%');
$('#uploadStatus').html('<img src="assets/img/loading.gif"/>');
},
error:function(){
$('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
},
success: function(resp){
r = JSON.parse(resp);
batchResult = 'ok';
// process the answer
$('#uploadStatus').empty();
for (var k = 0; k < r.length; k++) {
var fileResult = r[k];
var fileName = fileResult.file;
if (fileResult.type == 'error') {
var errText = fileResult.text;
batchResult = 'error';
$('#uploadStatus').append('<p style="color:#EA4335;">File "'+ fileName +'" ' + errText + '</p>');
} else {
$('#uploadStatus').append('<p style="color:#28A74B;">File "'+ fileName +'" was uploaded successfully!</p>');
}
}
// general result
if(batchResult == 'ok'){
$('#uploadForm')[0].reset();
$('#uploadStatus').append('<p style="color:#28A74B;">All Files were uploaded successfully!</p>');
} else if(batchResult == 'error'){
$('#uploadStatus').append('<p style="color:#EA4335;">Error uploading some or all files.</p>');
}
}
});
});
// File type validation & inform files selected
$("#fileInput").change(function(){
var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
var file = this.files[0];
var fileType = file.type;
if(!allowedTypes.includes(fileType)){
$("#fileInput").val('');
alert_error("Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF");
return false;
}
// show which file selected (or how many if > 1)
let filenames = [];
let files = document.getElementById("fileInput").files;
if (files.length > 1) {
filenames.push("Total Files (" + files.length + ")");
} else {
for (let i in files) {
if (files.hasOwnProperty(i)) {
var fname = files[i].name;
// up to 40 length or add ..
fname = fname.replace(/(.{40})..+/, "$1&hellip;");
filenames.push(fname);
}
}
}
// show in label
$(this)
.next(".custom-file-label")
.html(filenames.join(","));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment