File Uploads using Zend_Form

File uploads can be managed quite easily using Zend_Form. First off, create a Zend_Form instance and add a Zend_Form_Element_File element, representing the file-input element. Make sure to set the encoding type to multipart/form-data:

class Form_FileUpload extends Zend_Form {
    
    public function init() {

        $this->setAttrib('enctype', 'multipart/form-data');

        $element = new Zend_Form_Element_File('image');
        $element->setLabel('Some picture');
        $element->addValidator('Count', false, 1);
        $element->addValidator('Size', false, 204800);
        $element->addValidator('Extension', false, 'jpg,png,gif');
        $element->setRequired(true);

        $this->addElement($element);

        $this->addElement('text', 'someText', array(
            'filters' => array('StringTrim'),
            'label' => _('Some Text'),
            'decorators' => array(
                'viewHelper', array(
                    'Label', array('class' => 'label')
                ),
                'Errors'
            ),
            'validators' => array(
                array('StringLength', true, array(5, 255))),
            'id' => 'SomeText'
        ));
}

Now that we have a form let’s add the logic in the corresponding controller. We only need one action (imageAction) to process POST requests and GET requests:

public function imageAction() {

  $form = new Form_FileUpload();

  if ($this->getRequest()->isPost()) {
    $post = $this->getRequest()->getPost();

    if ($form->isValid($post)) {
     $upload = new Zend_File_Transfer_Adapter_Http();
     $upload->setDestination(realpath(APPLICATION_PATH . '\..\data\upload'));

     try { //be sure to call receive() before getValues()
       $upload->receive();
     } catch (Zend_File_Transfer_Exception $e) {
       $e->getMessage();
     }

     $formData = $form->getValues(); //be sure to call this after receive()

     $filename = $upload->getFileName('image'); //optional info about uploaded file
     $filesize = $upload->getFileSize('image');
     $filemimeType = $upload->getMimeType('image');

     $dstFilePath = '/images/'.$filename;

     $filterFileRename = new Zend_Filter_File_Rename(array('target' => $dstFilePath, 'overwrite' => true));
     $filterFileRename->filter($filename); //move uploade file to destination
   }
 }

 $this->view->form = $form;
}

That’s all there is to it. receive() processes the uploaded file, i.e. checks if everything went well. In order to move uploaded files to certain destination folders you can use Zend_Filter_File_Rename. Unlike the name suggests it does not only rename files but also is capable of moving files.

Make sure to call receive() before getValues() as Zend_Form otherwise messes up the file upload.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *