zend-frameworkfile-uploadzend-formzend-file

How to use Zend_File_Transfer?


I have been using normal file upload element to upload files and validate them. But recently, I found out that implementing a Zend_file_tranfer gives much control over the file.

I am searched Everywhere in the internet searching for a simple example to get started with it, but none of them show how they are linked to the element. I dont know where to create the object of Zend_File_Transfer, and how to add it to the element? I basically dont know, how to use it.

Can anyone give me a beginners example of using zend_File_tranfers, in both zend_form and Zend_Controller_Action


Solution

  • When you create your form do something like this in your form:

    $image = $this->getElement('image');
    //$image = new Zend_Form_Element_File();
    $image->setDestination(APPLICATION_PATH. "/../data/images"); //!!!!
    $extension = $image->getFileName();
    if (!empty($extension))
        {
            $extension = @explode(".", $extension);
            $extension = $extension[count($extension)-1];
            $image->addFilter('Rename', sprintf('logo-%s.'.$extension, uniqid(md5(time()), true)));
        }
    
    $image
        ->addValidator('IsImage', false, $estensioni)//doesn't work on WAMPP/XAMPP/LAMPP
        ->addValidator('Size',array('min' => '10kB', 'max' => '1MB', 'bytestring' => true))//limit to 200k
        ->addValidator('Extension', false, $estensioni)// only allow images to be uploaded
        ->addValidator('ImageSize', false, array(
                'minwidth' => $img_width_min,
                'minheight' => $img_height_min,
                'maxwidth' => $img_width_max,
                'maxheight' => $img_height_max
                )
            )
        ->addValidator('Count', false, 1);// ensure that only 1 file is uploaded
    // set the enctype attribute for the form so it can upload files
    $this->setAttrib('enctype', 'multipart/form-data');
    

    Then when you submit your form in your controller:

    if ($this->_request->isPost() && $form->isValid($_POST)) {
                $data = $form->getValues();//also transfers the file
    ....