Cakephp validating file upload "multiple"

Lalith Mohan

I'm trying to validate a cakephp file upload

The following is the input in my view

<?php echo $this->Form->input('images.', array('type' => 'file', 'multiple', 'label'=>'Upload Images to your gallery')); ?>

This is the html code I get in the browser

<input type="file" required="required" id="ProjectImages" multiple="multiple" name="data[Project][images][]" />

The following is the code in my model for validation

'images[]' => array(
        'extension' => array(
            'rule' => array(
                'extension' => array('jpeg', 'png', 'jpg'),
                'message' => 'Please supply valid images'
            )
        ),
        'size' => array(
            'rule' => array('fileSize', '<=', '2MB'),
            'message' => 'Image must be less than 2MB'
        )
    )

I've also tried to validate with 'image' as the field name but both do not work. The files are uploading correctly but the validation is not working.

Please help. Thank you

Abijeet Patro

Please check the thread linked here - Cakephp: Multiple files upload field sets to required automatically

I would suggest that you try to name the validation in the model as images rather than images[].If that still doesn't work, what I would suggest is for you to write a custom beforeSave function in your model and handle the validation yourself. You can use the following functions to do the validation.

public function isValidImageFile($filename) {
    if($this->checkFileUploadedName($filename) && 
        $this->checkFileUploadedLength($filename) && 
            $this->checkImgFileExtn($filename)) {
        return true;
    }
    return false;
}

private function checkFileUploadedName($filename)
{
    return (bool) ((preg_match("`^[-0-9A-Z_\.]+$`i",$filename)) ? true : false);
}

private function checkFileUploadedLength($filename)
{
    return (bool) ((mb_strlen($filename,"UTF-8") < 225) ? true : false);
}

private function checkImgFileExtn($filename) {
    $file_parts = pathinfo($filename);
    $supportedFileTypes =  array('jpg', 'png', 'jpeg', 'bmp');
    if(in_array(strtolower($file_parts['extension']), $supportedFileTypes)) {
        return true;
    }
    return false;
}

You could another method there to check the file size. You can check filesize using the php - filesize method.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related