I've put together pieces of codes online to do a ajax file upload. I am able to get the code to work, my php file is able to receive the files and upload it in tmp folder.
My problem, however, is that when i use the beforeSend in the ajax call to check the file, the error is called, but "return false" doesn't stop the ajax call. The Ajax is still submitted calling the PHP script.
I want the file check to be done on client side (of course PHP side will do once more), and stop if it doesn't match my requirement.
This is a avatar upload function.
$(document).ready(function() {
$('#profileupload').on('change',function(e) {
var formData = new FormData();
formData.append('action', 'upload_profile_image');
formData.append('nonce', 'nonce');
// Main magic with files here
formData.append('image', $('input[type=file]')[0].files[0]);
alert('here');
console.log(formData);
$.ajax({
url: 'ajaxurl',
type: 'POST',
dataType: 'json',
data: formData,
beforeSend: beforeSubmit(),
contentType: false,
processData: false,
success: function (d) {
console.log(d);
}
});
function beforeSubmit(){
//check whether client browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var fsize = $('#profileupload')[0].files[0].size; //get file size
var ftype = $('#profileupload')[0].files[0].type; // get file type
//allow file types
switch(ftype)
{
case 'image/jpeg':
break;
default:
$("#output").html("<b>"+ftype+"</b> Unsupported file type!");
console.log('false upload');
return false
}
//Allowed file size is less than 5 MB (1048576 = 1 mb)
if(fsize>5242880)
{
alert("<b>"+fsize +"</b> Too big file! <br />File is too big, it should be less than 5 MB.");
console.log('false upload');
return false
}
}
else
{
//Error for older unsupported browsers that doesn't support HTML5 File API
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
return false
}
}
});
});