Search code examples
phpfile-uploadzend-framework2

ZF2 Handling File Uploads. How to access the uploaded files?


I have seen a lot of questions and information in manuals about creating a form to upload files. I have been able to setup a form to handle file uploads. Is there any Zend based code for working with the files after they've been downloaded.

Every tutorial or manual reference seems to have something similar to:

if ($form->isValid()) {
    //
    // ...Save the form...
    //
}

I can manage uploads using the native php functions like move_uploaded_file. Am I missing something or does Zend just fall back to using the temp file name as the piece of data in some other piece of code?


Solution

  • It's in the manual

    http://framework.zend.com/manual/2.1/en/modules/zend.form.file-upload.html

    // File: MyController.php
    
    public function uploadFormAction()
    {
        $form = new UploadForm('upload-form');
    
        if ($this->getRequest()->isPost()) {
            // Make certain to merge the files info!
            $post = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
    
            $form->setData($post);
            if ($form->isValid()) {
                $data = $form->getData();
                // Form is valid, save the form!
                return $this->redirect()->toRoute('upload-form/success');
            }
        }
    
        return array('form' => $form);
    }
    

    Upon a successful file upload, $form->getData() would return:

    array(1) {
        ["image-file"] => array(5) {
            ["name"]     => string(11) "myimage.png"
            ["type"]     => string(9)  "image/png"
            ["tmp_name"] => string(22) "/private/tmp/phpgRXd58"
            ["error"]    => int(0)
            ["size"]     => int(14908679)
        }
    }
    

    Use the array what you get from $form->getData() to process the uploaded file.

    You can also set the target and rename it by using a filter called.

    Link below has nice explanation for that:

    http://framework.zend.com/manual/2.1/en/modules/zend.filter.file.rename-upload.html#zend-filter-file-rename-upload

    Hope this helps.