Created
May 30, 2022 02:52
-
-
Save KuJoe/be107bfc1e3dd3c2f54a02ec2bb83516 to your computer and use it in GitHub Desktop.
Javascript image upload function
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
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