简体   繁体   中英

Phalcon 4 validation multipart/form-data multiple

Is it possible to configure the file validator of Phalcon4, where it can validate multiple uploaded files?

I cannot find any documentation about multiple files upload, just file upload with different form fields: https://docs.phalcon.io/4.0/en/api/phalcon_validation#validation-validator-file

I can validate files which are uploaded one by one, but I need the form to handle multiple uploaded files at once.

Here is my code:

HTML

<input type="file" id="formFile" name="media[]" multiple>

Controller

$validation = new FileUploadValidation();
$validation->validate($_FILES);

FileUploadValidation.php

<?php

namespace App\Validator;

use Phalcon\Validation;
use Phalcon\Validation\Validator\File as FileValidator;

class FileUploadValidation extends Validation
{
    public function initialize()
    {
        $this->add(
            ['media'],
            new FileValidator(
                [
                    "maxSize"              => "2M",
                    "messageSize"          => ":field exceeds the max file size (:size)",
                    "allowedTypes"         => [
                        "image/jpeg",
                        "image/png",
                    ],
                    "messageType"          => "Allowed file types are :types",
                ]
            )
        );
    }
}

You can iterate on each file and validate it:

$validation = new FileUploadValidation();
   
foreach ($this->request->getUploadedFiles() as $file) { 
    $messages[] = $validation->validate($file);
}

if (count($messages)) {
  ...
}

Also, in your add definition you do not need to place an array, just a string (replace ['media'] with 'media' :

$this->add(
        'media',
        new FileValidator([...]}
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM