Validate uploaded file size through model

Hello,

I want to validate my uploaded file (image/doc/pdf/xls etc) for file size through model. The uploaded file should be less than 2 mb and document type can be either jpeg or pdf. Can anyone please help me through this . I am really struggling through this.

Hello,

You can use the following plugin that already includes, among other things, file size validation:

there is built in validation for it

https://api.cakephp.org/3.8/class-Cake.Validation.Validation.html#_uploadedFile

Graziel, Can you please provide me with the syntax . It would be easier for me. Thanx in advance.

$validator
->requirePresence(‘document’, ‘create’)
->notEmptyString(‘document’)
->add(‘document’, [

			[ 'rule' => ['extension',['pdf']], // default  ['gif', 'jpeg', 'png', 'jpg']
                'message' => __('Only pdf files are allowed.')],
				['rule' => ['fileSize', '<=', '1024'], 
                'message' => __('Image must be less than 1MB')]
            ]
			
		  );

This is my validator, It provides validation for extension but not for image size.Can you please help me through this.

i dont have currently any app with standard file upload so code can be a bit wrong but:

->uploadedFile('document', [
                'types' => [
                    'application/pdf', 
                    'images/jpeg',
                ],
                'maxSize' => 2 * 1024 * 1024
            ])

The validator setup looks OK.

means smaller than 1KB not 1 MB. Use e.g.

['fileSize', '<=', '1 MB'],

Yes it does. But it throws error in case of fileSize() as:
filesize(): stat failed for c:\xampp\tmp\php3f06.tmp [core\src\validation\validation.php, line 1297.

Is there some issue, if you can trace ?

That usually means that PHP can’t access the file, which seems curious if mime-type checking works. But I have no clue about PHP on Windows.

Do you move away the file manually before the validator can pick it up? I would go to said line, pause the execution there and check that the tmp file does actually exist.

Thanks for help. It works fine now.

Earlier, I moved my file before reaching the validator. Thanks for guiding.

cakephp 4.x: use separate ->add for every rule like this ->add(‘filed_name’,‘rule_name’,[
‘rule’ => [‘rule_name’, //parameters])