Skip to content

Instantly share code, notes, and snippets.

@KuJoe
Created May 30, 2022 02:52
Show Gist options
  • Save KuJoe/be107bfc1e3dd3c2f54a02ec2bb83516 to your computer and use it in GitHub Desktop.
Save KuJoe/be107bfc1e3dd3c2f54a02ec2bb83516 to your computer and use it in GitHub Desktop.
Javascript image upload function
function ajax_file_upload(file_obj) {
if(file_obj != undefined) {
$("h2").text("Starting upload...");
var form_data = new FormData();
for(i=0; i<file_obj.length; i++) {
if (!isImage(file_obj[i].name)) {
return failValidation("ext");
}
if (!validateSize(file_obj[i].size)) {
return failValidation("size");
}
form_data.append('file[]', file_obj[i]);
}
$.ajax({
type: 'POST',
url: 'upload.php',
contentType: false,
processData: false,
data: form_data,
dataType: 'json',
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//console.log(percentComplete);
$('h2').text('Uploading... ' + (Math.round(percentComplete * 100)) + '%');
}
}, false);
return xhr;
},
success: function (response) {
for(var index = 0; index < response.length; index++) {
$("h2").text("SUCCESS: "+response.length+" file(s) uploaded!");
var src = response[index];
$('#preview').append('<a href="'+src+'" target="_blank"><img src="'+src+'" width="100px;" height="100px"></a>');
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment