We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

File not coming up under $_POST after sending through ajax

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.

Because uploaded files are in $_FILES ...
Take a look at : https://docs.phalcon.io/en/3.2/request#uploading-files

Sorry, I didn't phrase my question in a very good way.

My problem is that I cannot validate the $_FILES input. It requires "a string", what do I do in this case. The 'string' in the validation finds its information from the $_POST array. How do I validate an image sent through ajax would be a proper title, and queston.

Because uploaded files are in $_FILES ...
Take a look at : https://docs.phalcon.io/en/3.2/request#uploading-files