Zend Framework 2 - get the new filename when uploa

2019-09-18 05:24发布

问题:

I am new to ZF2, and I am trying to upload a file and use the "randomize" option of the Rename file adapter filter inside the validator.

In the model I have this:

public function getInputFilter()
    {

        $inputFilter = new InputFilter();
        $inputFilter->add(array(
            'name' => 'picture',
            'required' => call_user_func(function() use ($prize_type_id){
                if(isset($this->picture_old) && !empty($this->picture_old)){
                    return false;
                }
                if(in_array($prize_type_id, array(1,2,3,5))){
                    return true;
                }else{
                    return false;
                }
            }),
            'validators' => array(
                array(
                    'name' => '\Pm\Validators\File\Image',
                    'options' => array(
                            'minSize' => '1',
                            'maxSize' => '1024',
                            'newFileName' => null,
                            'uploadPath' => './public/uploads/images/'
                    )
                )
            )
        ));
.....

And in the Image validator I have this:

$renameOptions['randomize'] = true;
$renameOptions['target'] = $uploadPath.$newFileName;
$this->filters[] = new Rename($renameOptions); 
$this->fileAdapter->setFilters($this->filters);
$this->fileAdapter->setValidators($this->validators); 
if ($this->fileAdapter->isValid()) { 
    $this->fileAdapter->receive();
    return $newFileName;
....

How can I get the $newFileName value back to the Model so I can write it to the database? Or do you have other suggestions to get this done?

Thank you !

回答1:

For file input there is a special FileInput class. You can find documentation here. For file uploads (also images) it is recommended to use this special input class inside your input-filter.

If you have problems implementing it just leave a comment.