html file
<form id="profileSettings" method="POST" enctype="multipart/form-data">
<input type="file" name="avatar" id="avatar" accept="image/x-png,image/jpeg,image/jpg" />
<input id="settings_submit" type="submit" name="submit" value="Update" />
</form>
javascript file
var avatar = $('#avatar')[0].files[0];
// create formdata
var data = new FormData();
data.append('avatar', avatar);
$.ajax({
url: baseUrl + 'settings/profile-settings',
type: 'post',
contentType: false,
processData: false,
data: data,
dataType: 'json',
success: function (feedback) {
// success
}
});
In my controller I use a Validator to validate my inputs. Everything gets sent except the files through $_POST.
$validation->add(['avatar'], new FileValidator([
'maxSize' => '2M',
'messageSize' => 'Avatar exceeds the max filesize (:max)',
'allowedTypes' => [
'image/jpeg',
'image/jpg',
'image/png',
],
'messageType' => 'Allowed file types are :types',
'maxResolution' => '800x600',
'messageMaxResolution' => 'Max resolution of avatar is :max'
]));
Now the problem is that the avatar isn't actually being found because it's not available in $_POST, so we can't validate it. We get this error Notice: Undefined index: avatar in D:\Programs\xampp\htdocs\articool\app\controllers\api\v1\SettingsController.php on line 98
if I type die(var_dump($_POST['avatar'])).
Does anyone know why the uploaded file is not available through $_POST when everything else sent through ajax is?
If I alert(avatar) in my javascript file, it alerts "undefined" if no image is uploaded, and "[object File]" if an image is uploaded.