我已经在线编写了一些代码来进行ajax文件上传。我能够让代码工作,我的php文件能够接收文件并将其上传到tmp文件夹中。
然而,我的问题是,当我在ajax调用中使用beforeSend来检查文件时,会调用错误,但是“return false”不会停止ajax调用。仍然提交Ajax调用PHP脚本。
我希望文件检查在客户端完成(当然PHP方将再次执行),如果不符合我的要求则停止。
这是一个头像上传功能。
$(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
}
}
});
});