Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Create Simple Upload Form with File Validation

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on August 31, 2012

Zend Framework 2 has Zend\File\Transfer component that can provide file transfer need for our application. We can add Files validator and pass error message to Zend\Form component object, that can be retrieve by view if process was failed. We can add another validator instead of Upload validator that registered by default in Http Adapter.


For example, i have upload form like this :


The code form will be like the following :

// filename : module/Test/src/Test/Form/ProfileForm.php
namespace Test\Form;

use Zend\Form\Form;

class ProfileForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('Profile');
        $this->setAttribute('method', 'post');
        $this->setAttribute('enctype','multipart/form-data');
        
        $this->add(array(
            'name' => 'profilename',
            'attributes' => array(
                'type'  => 'text',
            ),
            'options' => array(
                'label' => 'Profile Name',
            ),
        ));

        
        $this->add(array(
            'name' => 'fileupload',
            'attributes' => array(
                'type'  => 'file',
            ),
            'options' => array(
                'label' => 'File Upload',
            ),
        )); 
        
        
        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type'  => 'submit',
                'value' => 'Upload Now'
            ),
        )); 
    }
}

By that code above, we can call ProfileForm from action Controller :

// filename : module/Test/src/Test/Controller/ProfileController.php
namespace Test\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Test\Model\Profile;

class ProfileController extends AbstractActionController
{
    public function addAction()
    {
        $form = new ProfileForm();
        return array('form' => $form);
    }
}

For view, we can write the following :

// filename : module/Test/view/test/profile/add.phtml
$form = $this->form;
$form->setAttribute('action',
                    $this->url('Test/profile', //your route name ...
                               array('controller'=>'profile', 'action' => 'add'))); 
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formRow($form->get('profilename'));

echo $this->formRow($form->get('fileupload'));

echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

Just that, and form will be created. How we filter the input ? we can create input filter by following :

// filename : module/Test/src/Test/Model/Profile.php
namespace Test\Model;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Profile implements InputFilterAwareInterface
{
    public $profilename;
    public $fileupload;
    protected $inputFilter;
    
    public function exchangeArray($data)
    {
        $this->profilename  = (isset($data['profilename']))  ? $data['profilename']     : null; 
        $this->fileupload  = (isset($data['fileupload']))  ? $data['fileupload']     : null; 
    } 
    
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }
    
    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory     = new InputFactory();
             
            $inputFilter->add(
                $factory->createInput(array(
                    'name'     => 'profilename',
                    'required' => true,
                    'filters'  => array(
                        array('name' => 'StripTags'),
                        array('name' => 'StringTrim'),
                    ),
                    'validators' => array(
                        array(
                            'name'    => 'StringLength',
                            'options' => array(
                                'encoding' => 'UTF-8',
                                'min'      => 1,
                                'max'      => 100,
                            ),
                        ),
                    ),
                ))
            );
            
            $inputFilter->add(
                $factory->createInput(array(
                    'name'     => 'fileupload',
                    'required' => true,
                ))
            );
            
            $this->inputFilter = $inputFilter;
        }
        
        return $this->inputFilter;
    }
}

Now, we can set inputFilter to form from action controller, pass data post and file to form object, and check the validation :

// filename : module/Test/src/Test/Controller/ProfileController.php
namespace Test\Controller;

use Zend\Mvc\Controller\AbstractActionController;

use Test\Model\Profile,
    Test\Form\ProfileForm;

class ProfileController extends AbstractActionController
{
    public function addAction()
    {
        $form = new ProfileForm();
        $request = $this->getRequest();  
        if ($request->isPost()) {
            
            $profile = new Profile();
            $form->setInputFilter($profile->getInputFilter());
            
            $nonFile = $request->getPost()->toArray();
            $File    = $this->params()->fromFiles('fileupload');
            $data = array_merge(
                 $nonFile, //POST 
                 array('fileupload'=> $File['name']) //FILE...
             );
            
            /** if you're using ZF >= 2.1.1  
              *  you should update to the latest ZF2 version
              *  and assign $data like the following 
                   $data    = array_merge_recursive(
                        $this->getRequest()->getPost()->toArray(),           
                       $this->getRequest()->getFiles()->toArray()
                   );
             */

            //set data post and file ...    
            $form->setData($data);
             
            if ($form->isValid()) {
                //HEY, FORM IS VALID...
            } 
        }
         
        return array('form' => $form);
    }
}

If form is valid, we can save file to directory we desired by \Zend\File\Transfer\Adapter\Http component, and add other validation, for example, add Size validation to validate minimal size will be accepted to be uploaded.

//import Size validator...
use use Zend\Validator\File\Size;
.........
if ($form->isValid()) {
    
    $size = new Size(array('min'=>2000000)); //minimum bytes filesize
    
    $adapter = new \Zend\File\Transfer\Adapter\Http(); 
    //validator can be more than one...
    $adapter->setValidators(array($size), $File['name']);
    
    if (!$adapter->isValid()){
        $dataError = $adapter->getMessages();
        $error = array();
        foreach($dataError as $key=>$row)
        {
            $error[] = $row;
        } //set formElementErrors
        $form->setMessages(array('fileupload'=>$error ));
    } else {
        $adapter->setDestination(dirname(__DIR__).'/assets');
        if ($adapter->receive($File['name'])) {
            $profile->exchangeArray($form->getData());
            echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
        }
    }  
} 

Finally, the complete controller source code :

// filename : module/Test/src/Test/Controller/ProfileController.php
namespace Test\Controller;

use Zend\Mvc\Controller\AbstractActionController;
    
use Test\Model\Profile,
    Test\Form\ProfileForm;

use Zend\Validator\File\Size;

class ProfileController extends AbstractActionController
{
    public function addAction()
    {
        $form = new ProfileForm();
        $request = $this->getRequest();  
        if ($request->isPost()) {
            
            $profile = new Profile();
            $form->setInputFilter($profile->getInputFilter());
            
            $nonFile = $request->getPost()->toArray();
            $File    = $this->params()->fromFiles('fileupload');
            $data = array_merge(
                 $nonFile,
                 array('fileupload'=> $File['name'])
             );
            //set data post and file ...    
            $form->setData($data);
             
            if ($form->isValid()) {
                
                $size = new Size(array('min'=>2000000)); //minimum bytes filesize
                
                $adapter = new \Zend\File\Transfer\Adapter\Http(); 
                $adapter->setValidators(array($size), $File['name']);
                if (!$adapter->isValid()){
                    $dataError = $adapter->getMessages();
                    $error = array();
                    foreach($dataError as $key=>$row)
                    {
                        $error[] = $row;
                    }
                    $form->setMessages(array('fileupload'=>$error ));
                } else {
                    $adapter->setDestination(dirname(__DIR__).'/assets');
                    if ($adapter->receive($File['name'])) {
                        $profile->exchangeArray($form->getData());
                        echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
                    }
                }  
            } 
        }
         
        return array('form' => $form);
    }
}

You can separate File Transfer process in another function or model if you want. If Size validation failed, the form will show this :

References :
1.http://stackoverflow.com/questions/11690320/how-do-i-pass-file-and-post-data-into-a-form
2.http://zf2.readthedocs.org/en/latest/user-guide/forms-and-actions.html

Advertisements

270 Responses

Subscribe to comments with RSS.

  1. Foofoonych Barbarychev-Barbarushking said, on October 6, 2012 at 4:07 pm

    Oh thanks man, you helped so much

  2. samsonasik said, on October 7, 2012 at 12:41 am

    You’re welcome 😉

  3. Gildus (@gildus) said, on October 11, 2012 at 12:07 am

    Perfect, direct and easy, thanks @samsonasik.

  4. samsonasik said, on October 11, 2012 at 1:08 pm

    You’re welcome 😉

  5. dimuthu said, on November 2, 2012 at 11:05 am

    nice work man

  6. hermes said, on November 17, 2012 at 8:56 pm

    Thanks a lot man, you saved me a lot of time. stay blessed

  7. quy said, on November 18, 2012 at 9:53 am

    $adapter->setDestination(dirname(__DIR__).’/assets’);
    thanks, but i don’t understand this destination.can you explain this please

    • samsonasik said, on November 18, 2012 at 11:20 am

      it set the destination of upload files to module/Module_NAME/src/Module_NAME/assets.

      • Mudit said, on June 9, 2015 at 5:07 pm

        I select the file to upload and click on the button but when I check the directory there is no file there. I’m using Zend Framework 2.4.2 . Please Help.

      • samsonasik said, on June 10, 2015 at 8:00 am

        check the directory permissions, debug with error_reporting(E_ALL); and var_dump()

  8. sanoche16 said, on November 19, 2012 at 10:02 pm

    Thanks a lot! very helpful!!

  9. Mohamed said, on November 22, 2012 at 12:26 pm

    amazing tut

    but need some help to rename uploaded file

    in zf1

    $file_upload_element->addFilter(‘Rename’, $newFileName);

    how to do this in zf2

  10. samsonasik said, on November 22, 2012 at 5:28 pm

    Rename filter is now under Zend\Filter\File namespace. so use like the following :

    $adapter->setDestination(dirname(__DIR__).'/assets');
    foreach ($adapter->getFileInfo() as $info) {
        $adapter->addFilter('File\Rename',
            array('target' => $adapter->getDestination().'/newname.png',
            'overwrite' => true));
        
        if ($adapter->receive($info['name'])) {
            $file = $adapter->getFilter('File\Rename')->getFile();
            print_r($file[0]['target']);
        }
    }
    
    • Mohamed said, on November 22, 2012 at 10:38 pm

      Thanks A lot .
      Gazak Allah Khayran.

  11. Juan Escobar said, on November 22, 2012 at 10:41 pm

    Hello Samsonasik, I have a question. What is most recommend for save a file, a database or a folder in the filesystem? I need manage the file: overwrite, delete.
    Thank you.

    • samsonasik said, on November 22, 2012 at 10:56 pm

      I recommend save a file in filesystem, save only a name of files in database.

      • Juan Escobar said, on November 24, 2012 at 11:52 am

        Thank you from reply, some special motive for save in filesystem? and for delete it you would use the unlink function? 🙂 Greetings.

      • samsonasik said, on November 24, 2012 at 12:43 pm

        you should save something in database as small as possible to faster your query. for deleting, you can use what you want. unlink, shell_exec, system, etc.

  12. Mohamed said, on November 24, 2012 at 8:39 pm

    back
    if u have more than one file upload element u should specifiey in the valid like this otherwise u will get error that the other files not set

    [php]
    if (!$adapter->isValid($File[‘name’])){
    [/php]

    I have one thing in my mind why Zend Form isValid() not validating files
    also the adapter to be included within file element and add validator add validation to adapter

    I need to know what’s wrong on that ?
    why it’s not implemented on ZF2 at least to be option

  13. Benjamin said, on November 25, 2012 at 12:56 am

    Hi Samsonasik, first of all thanks for this great tut, its hard to find clean ones like this one, and secondly how about if i want to validate the extension, i still dont understand how to use ZF2 validators in the inputfilter

  14. samsonasik said, on November 25, 2012 at 1:50 am
    $extensionvalidator = new \Zend\Validator\File\Extension(array('extension'=>array('jpg','png')));
    $adapter->setValidators(array($extensionvalidator), $File['name']);
    
  15. Foofoonych Barbarychev-Barbarushking said, on November 26, 2012 at 10:45 am

    samsonasik, can you opt out me?

    • Mohamed said, on November 26, 2012 at 10:53 am

      I think u have to wait zf 2.1
      u will not imagine how easy it is to use file as inputfilter

      try to download development version of zf from github and use it dont waste time with file\http adapter

  16. Fredrik Wahlqvist (@FredWahlqvist) said, on November 29, 2012 at 5:16 am

    Hi Abdul,
    great tutorial, I am currently following this but keep getting
    “Value is required and can’t be empty” when i try to submit the forms, where do you recomend me to start looking for errrors as I have not been able to track it down yet.

    • samsonasik said, on November 29, 2012 at 6:04 am

      what zf2 version you are using ? i suggest to update to the latest release first.

      try debug first 

      if ($form->isValid()) { 
         ...........
      } else {
          echo '<pre>';
          print_r($form->getMessages()); die:
      }
      
      • Fredrik Wahlqvist (@FredWahlqvist) said, on November 30, 2012 at 5:06 am

        Thanks for a quick reply!
        When I use this in add.phtml i ge t
        “Fatal error: Uncaught exception ‘Zend\Form\Exception\DomainException’ with message ‘Zend\Form\Form::isValid is unable to validate as there is no data currently set’ in C:\..”
        Any suggestions on next steps?

        Once again thanks!

      • Fredrik Wahlqvist (@FredWahlqvist) said, on November 30, 2012 at 5:44 am

        If you have a min spare it would be great if you could have a look, the code is available @
        https://github.com/fwahlqvist/wdev-fileupload
        Many Thanks

      • samsonasik said, on November 30, 2012 at 2:43 pm

        You have not yet made ​​the assets folder in your ModuleName\src\ModuleName

  17. Fredrik Wahlqvist (@FredWahlqvist) said, on December 1, 2012 at 8:12 am

    Hi Abdul, I have created the assets folder in the root of the module but no luck, also when I use the debug as you suggested I get that the fileupload is empty But the value for the name is ok when I populate both a file a Nd the name.

    Any further suggestions?
    Ps will update my git tomorrow as I rewrote most of it to avoid namespace claches

    Once again thanks
    Fred

  18. Fredrik Wahlqvist (@FredWahlqvist) said, on December 2, 2012 at 12:49 am

    Thanks Abdul, will do!
    Best
    Fred

  19. Dre said, on December 4, 2012 at 8:03 pm

    Hi Samsonasik,

    I’m trying to upload the file in the “/public/images/” folder, but I can’t find the path I need to insert in the ->setDestination().

    Could you help me?

    • samsonasik said, on December 4, 2012 at 8:36 pm
      $adapter->setDestination('./public/images');
      
      • Dre said, on December 5, 2012 at 9:01 pm

        Thanks Samsonasik, I’ve figure out that something was going wrong and I solved with

        $string = ‘/../../../../../public/images/’;
        $url = dirname(__FILE__).$string;

        though I’m happy to use a more correct way.

        And what if I’d like to rename the file before the upload is completed?

        Thanks again, I’ve appreciated your help.

      • samsonasik said, on December 5, 2012 at 11:53 pm

        if you’re using ZendSkeletonApplication as basic skeleton. You should found :

        chdir(dirname(__DIR__));
        

        and you should only write ‘./public/images’;

  20. craig said, on January 26, 2013 at 9:58 pm

    @somsonasik – great tutorial. Thanks so much.

    I have been trying your extension validator code higher in the comments, but the validator fails. Looking at what gets passed to the extension validator it is a file with a .tmp extension, yet I pass a jpg. The tmp file is in the temp folder.

    I pass the validator as follows.

    $extensionvalidator = new Extension(array(‘extension’=>array(‘jpg’,’png’)));
    $adapter -> setValidators( array($size, $count, $extensionvalidator ) , $file );

  21. craig said, on January 27, 2013 at 7:53 am

    Thanks, I should have speciifed that I ended up moving the fileupload code into a model.

    I pass the file name through a parameter called $file, but it should be the same as your script. For instance, I just checked the variable I passed in and I get the file name “181582878_full.jpg”.

    I checked the isValid() method in extension validator and placed a called to echo $value to see what is passed in. It appears that the method is passed C:\Windows\Temp\php29D.tmp then fails as a tmp is not a jpg.

    • samsonasik said, on January 27, 2013 at 4:56 pm

      try to debug by assign a variable using reference.

      $file = & $_FILES[‘fileupload’][‘name’] ;

  22. craig said, on January 30, 2013 at 8:50 am

    I tried this and get the same response. Looking at the validator is passed two parameters and accepts only one. The way it is currently coded it will get passed the value of the .tmp file and the $_FILE array. Unfortunately as the .tmp file is passed first this cause the extension.php validator to fail. This looks like a bug to me, although I wonder if it could be an issue with the verison I am working off as it is obviously working for you. I will keep playing thanks for your help.

  23. samsonasik said, on January 30, 2013 at 3:44 pm

    try another way. ZF 2.1 dev is now release. update your zf2 here https://github.com/zendframework/zf2 , and then, you can try https://github.com/cgmartin/ZF2FileUploadExamples for upload examples 😉

  24. Pavy said, on January 31, 2013 at 7:30 pm

    Hi….

    I have followed steps as shown by you above,…

    I can hit localhost/test/profile/add which gives me an error as “Route with name “Test” not found”

    If I remove the action attribute, everything works fine.
    Here is module.config.php
    array(
    ‘routes’ => array(
    ‘home’ => array(
    ‘type’ => ‘segment’,
    ‘options’ => array(
    ‘route’ => ‘/’,
    ‘defaults’ => array(
    ‘controller’ => ‘Test\Controller\Profile’,
    ‘action’ => ‘add’,
    ),
    ),
    ),
    // The following is a route to simplify getting started creating
    // new controllers and actions without needing to create a new
    // module. Simply drop new controllers in, and you can access them
    // using the path /application/:controller/:action
    ‘test’ => array(
    ‘type’ => ‘Literal’,
    ‘options’ => array(
    ‘route’ => ‘/test’,
    ‘defaults’ => array(
    ‘__NAMESPACE__’ => ‘Test\Controller’,
    ‘controller’ => ‘Profile’,
    ‘action’ => ‘add’,
    ),
    ),
    ‘may_terminate’ => true,
    ‘child_routes’ => array(
    ‘default’ => array(
    ‘type’ => ‘Segment’,
    ‘options’ => array(
    ‘route’ => ‘/[:controller[/:action]]’,
    ‘constraints’ => array(
    ‘controller’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
    ‘action’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
    ),
    ‘defaults’ => array(
    ),
    ),
    ),
    ),
    ),
    ),
    ),

    ‘controllers’ => array(
    ‘invokables’ => array(
    ‘Test\Controller\Profile’ => ‘Test\Controller\ProfileController’
    ),
    ),
    ‘view_manager’ => array(
    ‘template_path_stack’ => array(
    ‘test’ => __DIR__ . ‘/../view’,
    ),
    ),

    );

  25. Pavy said, on February 1, 2013 at 12:58 pm

    Hi,

    I have one more question on namespace.

    Here I have created profile controller as per ur post…
    The name space used is Test\Controller
    Folder structure goes like this – src/Test/Controller/ProfileController.php

    What if I want to create new controller under src/Test/Controller/USerCOntroller.php??
    How will the name space apply??
    Can I use Test\Controller or should I use a different one??

    • samsonasik said, on February 1, 2013 at 1:19 pm

      you can use Test\Controller as __NAMESPACE__ in route.

  26. Pavy said, on February 1, 2013 at 1:25 pm

    I mean, in case of namespace Test\Controller I tried writing Test\PController..

    when I hit test/profile/add , it gives me blank page

    in module.config.php, where should I change the namespace implementation?

    • samsonasik said, on February 1, 2013 at 1:27 pm

      You should write Test\Controller\PController, not Test\PController

  27. Pavy said, on February 1, 2013 at 1:30 pm

    Can you give me an explanation ?? That makes me undertsand …since I m new to ZF2..

  28. Pavy said, on February 1, 2013 at 1:34 pm

    Do you mean my namspace should be Test\Controller\PController ??

    As I have shown my module.config.php earlier, where does the namespace apply?

  29. ebalicat said, on February 6, 2013 at 9:53 am

    OK. What about when the form is not valid because the Profile Name, for example, is required and user leave it blank, how can I save on the form the previously uploaded file so that it will not be uploaded again and again?

    • samsonasik said, on February 6, 2013 at 8:50 pm

      there is no deal for it for security reason. You should not save it until it verified.

      • ebalicat said, on February 7, 2013 at 8:15 am

        What if there are many elements in a form, and the user only forgot one required element, and then in his second attempt he fills that element but then forgets to fill in the file input element, would it be good to save that input so that he will not forget to input that file again? Just analyzing on the user’s perspective. 🙂

        Otherwise, I have found out that https://github.com/cgmartin/ZF2FileUploadExamples has that sample. Anyways, thanks @samsonasik

  30. Aamir said, on February 6, 2013 at 1:35 pm

    how i unlink the perticular image according to its name stored in database..please provide code for it…i know logic that select that field and unlink file bt in zend i dont know this.plz help….

    • samsonasik said, on February 6, 2013 at 8:51 pm

      saving file should be in filesystem. save name of file is on db. if you want to unlink, unlink the file, update selected rows of table.

  31. Maurício Silva said, on February 28, 2013 at 3:08 am

    Do you mind of writing a ZF 2.1+ tutorial for file upload? Could you include also tips of how can we do on the edit form with upload file?

  32. Gul said, on March 1, 2013 at 8:41 pm

    I am getting this error. Array ( [fileUploadErrorIniSize] => File ” exceeds the defined ini size )
    where as i am trying to upload a 85 Bytes size file. My default memory size in PHP.ini is 8M also when i apply this $this->setAttribute(‘enctype’,’multipart/form-data’);. I get Validation error that File upload field is required.

  33. vikas said, on March 14, 2013 at 8:13 pm

    how to fetch image from database in zend framewwork2 and which code i shall write in phtml file current i write
    <img src="escapeHtml($user->image);?>”/> where $user is array and image is the field of database but i am not getting the image i get only name of the image which is in database

    • vikas said, on March 14, 2013 at 8:15 pm

      how to fetch image from database in zend framewwork2 and which code i shall write in phtml file current i write
      <img src="escapeHtml($user->image);?>”/> where $user is array and image is the field of database but i am not getting the image i get only name of the image which is in database

      • samsonasik said, on March 15, 2013 at 2:27 am

        you should save image name only in the db. for example : image.jpg saved in the db, save your file (image.jpg) in file system. and call by

        <img src="/the/path/to/<?php echo $imagefromdb; ?> " />
        
  34. sivabalan said, on March 28, 2013 at 5:38 pm

    i want upload a image. image uploading is working fine. but also want to display it after uploading . Suppose user goes to edit profile option means there old image should be display. when user uploading new image means it should be replaced. Please help me to do this

    • samsonasik said, on March 30, 2013 at 3:01 am

      this is very easy. you just should save a filename to the db, placed the filename in the directory,and show it. for edit, delete old filename if upload new file, change current filename in db with uploaded filename.

  35. alona said, on April 5, 2013 at 5:29 pm

    Hi,

    First of all thanks a lot for the explanation.
    I need to upload files but I have formcollection,
    so I get warnings about \Zend\File\Transfer\Adapter\Http() when it goes to file_exists() and it receives array ($value[“name] is received as array not as a path…)

    I’ve previously build a simple form, and it works fine..what I have to change to make it work for the formcollection (every collection has file input…and maybe in the future I’d like to make it possible to add more file inputs to each of them )..

    Thanks in advance.

    Alona.

  36. zack said, on April 8, 2013 at 5:01 pm

    in zf1, I simply put anything in Form file (like: FormUser.php):
    +) create form
    +) filter
    +) validator
    +) set destination
    No thing in controller, in controller just call form.
    In your tut I see many code in controller, so have we other way to do FORM UPLOAD, thanks !

  37. zack said, on April 9, 2013 at 9:17 am

    Thanks you very much, in this example you post above, I see the author using Input filter like below:
    $inputFilter = new InputFilter\InputFilter();

    // File Input
    $file = new InputFilter\FileInput(‘file’);
    $file->setRequired(true);
    $file->getFilterChain()->attachByName(
    ‘filerenameupload’,
    array(
    ‘target’ => ‘./data/tmpuploads/’,
    ‘overwrite’ => true,
    ‘use_upload_name’ => true,
    )
    );
    $inputFilter->add($file);

    But I often using input filter like:
    $inputFilter = new InputFilter();
    $factory = new InputFactory();
    $inputFilter->add($factory->createInput(array(
    ‘name’ => ‘password’,
    ‘required’ => true,
    ‘filters’ => array(
    array(‘name’ => ‘StripTags’),
    array(‘name’ => ‘StringTrim’),
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘StringLength’,
    ‘options’ => array(
    ‘encoding’ => ‘UTF-8’,
    ‘min’ => 10,
    ‘max’ => 100,
    ),
    ),
    ),
    )));

    So, could you tell me how to do form upload follow second style. Thanks you !

    • samsonasik said, on April 10, 2013 at 1:52 am

      you can follow my post ;). it’s just a choice about simplicity / flexibility.

  38. outman said, on April 9, 2013 at 9:46 pm

    salam samsonasik said
    i hafe folow your tutorial it great work congratutation, i have implement multi fils upload and i want ask you if you can say me hoe to rename a fils? i use version zf2
    chukran thanks

    • samsonasik said, on April 10, 2013 at 1:55 am

      based on my post, you can do like the following :

      $adapter->setDestination(dirname(__DIR__).'/assets');
      foreach ($adapter->getFileInfo() as $info) {
          $adapter->addFilter('File\Rename',
              array('target' => $adapter->getDestination().'/newname.png',
              'overwrite' => true));
           
          if ($adapter->receive($info['name'])) {
              $file = $adapter->getFilter('File\Rename')->getFile();
              print_r($file[0]['target']);
          }
      }
      

      but i recommend cgmartin’s way : https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Form/CollectionUpload.php , he is expert about it 😉

      • outman said, on April 10, 2013 at 2:23 am

        thank you soo mutch, was soo helpful

      • samsonasik said, on April 10, 2013 at 2:53 am

        you’re welcome 😉

      • outman said, on April 10, 2013 at 5:24 am

        how can i get a name for a new file from:


        $adapter->addFilter('File\Rename',
        array('target' => dirname(__DIR__).'/assets/img.png',
        'randomize' => true,
        'overwrite' => true));

      • samsonasik said, on April 10, 2013 at 5:33 am
        .....
                print_r($info)
                $file = $adapter->getFilter('File\Rename')->getFile();
                print_r($file[0]['target']);
        ....
        
  39. outman said, on April 10, 2013 at 5:39 am

    thany you for your replay.
    but the result is : C:\…\module\Account\src\Account/assets/img.png
    i think that i have change something

    • samsonasik said, on April 10, 2013 at 5:43 am
      echo basename($file[0]['target']);
      
      • outman said, on April 10, 2013 at 5:47 am

        it print just img.png. 😦

      • samsonasik said, on April 10, 2013 at 5:56 am

        i think the problem is when you’re using randomize and targetting, i’m not try it yet, i’ll look at it.

      • samsonasik said, on April 10, 2013 at 6:51 am

        for now, i suggest to follow cgmartin’s way 😉

    • nomaanp153 said, on June 22, 2013 at 4:26 pm

      Hi,
      @outman This would help you….
      $adapter->setDestination(dirname(__DIR__).’/assets’);
      foreach ($adapter->getFileInfo() as $info) {
      $adapter->addFilter(‘File\Rename’,
      array(‘target’ => $adapter->getDestination().’/newname.png’,
      ‘overwrite’ => true));

      if ($adapter->receive($info[‘name’])) {
      $filename = $adapter->getFileName();
      echo $filename;
      }
      }

  40. Salman said, on April 16, 2013 at 2:17 pm

    hello Abdul
    How can I make multiple file uploads instead of single file.. I am using your project “SanUpload”, I am new to zend and need a little help.. thankyou
    Thanks in Advance

  41. Musafar said, on April 19, 2013 at 6:11 pm

    I have been developing a signup form. ZF2 docs helped me much and some error helped me to reach here 😉
    First of all, thanks very much. I implemented this and is working 😀

    Few doubts:
    1. I want the destination folder to be ‘/public/img/’. How to get base path in controller? (I thought files should be saved inside public. Please correct me if I am wrong)

    2. I am using ZF 2.0, but

    /** if you’re using ZF >= 2.1.1
    * you should update to the latest ZF2 version
    * and assign $data like the following
    $data = array_merge_recursive(
    $this->getRequest()->getPost()->toArray(),
    $this->getRequest()->getFiles()->toArray()
    );
    */
    if we are using this code, then what should be $File[‘name’] in
    $adapter->setValidators(array($size), $File[‘name’]);

    • samsonasik said, on April 19, 2013 at 7:09 pm

      1. if you’re using skeleton application, you will find

      chdir(dirname(__DIR__));
      

      in public/index.php which means Everything is relative to the application root now. so, you can set destination with

      $adapter->setDestination('./public//img');
      

      2.

      $File    = $this->params()->fromFiles('fileupload');
      
  42. Abdou said, on April 22, 2013 at 7:58 pm

    Hello,
    To download the file uploded ?

    • samsonasik said, on April 23, 2013 at 12:42 am

      try something like this in controller action :

      public function downloadAction()
      {
              $file = '/path/to/file.ext';
               
              $response = $this->getResponse();
              $response->getHeaders()
                   ->addHeaderLine('content-type', 'application/force-download')
                   ->addHeaderLine('content-length', filesize($file))
                   ->addHeaderLine('content-Description','File Transfer')
                   ->addHeaderLine('content-disposition', "attachment; filename=\"".basename($file)."\"");
              
              $response->setContent(file_get_contents($file));
               
              return $response;
      }
      
      • Abdou said, on April 23, 2013 at 7:53 am

        Thx Bro,
        I’m gone to try this 🙂

      • samsonasik said, on April 23, 2013 at 3:48 pm

        you’re welcome 😉

  43. ravikiran said, on May 7, 2013 at 2:05 pm

    i had used your above article in that i need to add current time stamp to a uploaded file, can you help me in this

    • samsonasik said, on May 8, 2013 at 1:51 am
      $adapter->setDestination(dirname(__DIR__).'/assets');
      foreach ($adapter->getFileInfo() as $info) {
          $adapter->addFilter('File\Rename',
              array('target' =>$adapter->getDestination().'/'.date('dmyHis').str_replace(" ", "",$File['name']),
              'overwrite' => true));
           
          if ($adapter->receive($info['name'])) {
              $file = $adapter->getFilter('File\Rename')->getFile();
              print_r($file[0]['target']);
          }
      }
      
  44. ravikiran said, on May 7, 2013 at 2:13 pm

    i am uploading .csv file how to give validation for upload only .csv file

    • samsonasik said, on May 8, 2013 at 1:49 am
      $extensionvalidator = new \Zend\Validator\File\Extension(array('extension'=>array('csv')));
      $adapter->setValidators(array($extensionvalidator), $File['name']);
      
      • ravikiran said, on May 8, 2013 at 6:42 pm

        Thank you for helping me,
        can you help me for doing pagination using jquery

  45. rocco said, on May 13, 2013 at 5:54 am

    Hi, it’s possible to integrate this upload with Amazon S3 or is a totaly different system ?
    I use the SDK AWS-PHP on gitub https://github.com/aws/aws-sdk-php and Uploadify or BlueImp System.

    I tried to use this example but i don’t able to manage the Filter/Destination and putObject of Aws sdk.

    Thanks in advance.

  46. Viha said, on May 15, 2013 at 6:26 pm

    Hi! Here’s a mistake when re-loading the form (when not passed validation) Help me please:
    Fatal error: Uncaught exception ‘Zend\View\Exception\InvalidArgumentException’ with message ‘Array provided to Escape helper, but flags do not allow recursion’

  47. Damjan said, on May 21, 2013 at 2:29 am

    How can I access the entire file name, including unique postfix, after it has been renamed? So I could save that name to database, which would be necessary for download.

  48. ravikiran said, on May 21, 2013 at 7:16 pm

    I am uploading .csv file which contains 4 files(codeid(int), codename(varchar), codeper(decimal), staeid(int) )
    1. how to check uploading file fields datatypes
    2. in above 1,4 field are mandatory

  49. […] Abdul Malik Ikhsan’s Blog […]

  50. Dexter said, on June 13, 2013 at 10:57 am

    Hi, Samsonasik.

    How do you rename the files that you uploaded using zf2 2.2? (more than 1 document)

    http://stackoverflow.com/questions/15781771/zf2-how-to-upload-files-more-than-1-file/17078862#17078862

    It only rename the first file.

    Cheers,
    Zf2 Student

  51. priyank prajapati said, on July 4, 2013 at 2:58 pm

    $error = array();
    foreach($dataError as $row)
    {
    $error = $row[];
    }
    $form->setMessages(array(‘upload’ => $error));

    in this line $error = $row[];

    Fatal error: Cannot use [] for reading in D:\root\xampp\htdocs\myproject\zendtest\module\Country\src\Country\Controller\CountryController.php on line 63

    so how can i solve it…

    i use ur all code

  52. priyank prajapati said, on July 4, 2013 at 8:16 pm

    $adapter = new \Zend\File\Transfer\Adapter\Http();
    $adapter->setValidators(array($size,$file[‘name’]));

    error can display here

    form is not valid

    so what can i do…

    all code can be copy past in ur site…

  53. Vitaliy Golovkа (@dudus_macacus) said, on July 11, 2013 at 10:29 pm

    i have question. how to get the filename and path file in controller?i want send to the db table field with file(e.x image) path

  54. Vimal raj said, on July 14, 2013 at 9:12 pm

    How to validate multiple file upload

  55. kalelc said, on July 16, 2013 at 3:34 am

    hello.. i have one problem.. in the moment upload files exception message:

    File:
    /home/carcol/workspace/kaozend/vendor/zendframework/zendframework/library/Zend/File/Transfer/Adapter/AbstractAdapter.php:942
    Message:
    The given destination is not writeable

    • samsonasik said, on July 16, 2013 at 4:37 am

      you must set permission to 777 the directory of destination.

      chmod -R 777 /path/to/destinationfolder
      
  56. thomas said, on July 24, 2013 at 8:22 pm

    Hi samsonasik

    i always get that my adapter is not valid.

    [CODE]

    public function save(array $data, $id = null){
    if (!$form->isValid()) {
    $this->setMessage(‘Please check your input!’);
    return false;
    }

    $adapter = new \Zend\File\Transfer\Adapter\Http();
    $File = $data[‘imageUpload’];

    //tried without validator criterias
    $adapter->setValidators(array(),$File[‘name’]);
    if (!$adapter->isValid()){
    echo ‘adapter not valid!’;
    $dataError = $adapter->getMessages();
    $error = array();
    foreach($dataError as $key=>$row)
    {
    $error[] = $row;
    } //set formElementErrors
    $form->setMessages(array(‘imageUpload’ => $error ));
    } else {
    echo ‘adapter is valid!’;
    $adapter->setDestination(‘./public/img/’);

    if ($adapter->receive($data[‘imageUpload’][‘name’])) {
    echo ‘adapter reveive data!’;
    $profile->exchangeArray($form->getData());
    echo ‘Profile Name ‘.$profile->profilename.’ upload ‘.$profile->fileupload;
    }else{
    echo ‘adapter do not receive data!’;
    }
    }
    //stopp here
    die();
    }
    [/CODE]

    I am using fileprg in the controller and then forward the prg to that save()-function, where i am doing the validation and image storing.

    Do you have any suggestion on how to get that solved?

    • samsonasik said, on July 25, 2013 at 1:13 am

      you forgot to initialize $form local variable.

      • thomas said, on July 25, 2013 at 1:30 pm

        Hi Sam,

        thanks for your reply.
        I did initialize the $form… just didnt paste it here…

        $form = $this->getForm($mode);
        $form->setData($data);

        The form ant the data object do have all the data stored temporarly.. so i guess there must be somehting wrong with the adapters validation?

        But i am not sure.

        Ah, another thing. is there a way to put code in here formated like your posts and replies?

      • samsonasik said, on July 25, 2013 at 4:04 pm

        you should debug $data is. read this about posting code at wordpress http://en.support.wordpress.com/code/posting-source-code/

  57. kalelc said, on July 25, 2013 at 2:50 am

    master 🙂 as I can modify the error messages? example:

    Minimum expected size for file is ‘100MB’ but ‘1.69MB’ detected to:

    Tamaño mínimo esperado para archivo es ‘100MB ‘pero ‘1 0.69 MB’ detecta

  58. Krishna said, on August 16, 2013 at 1:54 pm

    nice article but .. i have facing a problem like storing the files in file system…. as you said i tried with $adapter->setDestination(‘./public_adverts/images’); but it is working , i am using Zend 2 only… but the problem is .. later some days i will change my public_adverts folder to public only…. so how can i give the same dynamically.. otherwise is there any possible to give in configuration files. Please help me … i am very new to zend

    • samsonasik said, on August 16, 2013 at 2:01 pm

      you can read configuration from serviceManager, when you already write array config, you can call like the following :

      $config = $this->getServiceLocator()->get('Config');
      $public_area = $config['Your_config_public_area_array_config']
      
      • Krishna said, on August 16, 2013 at 4:33 pm

        Thanks for your reply . its helped me a lot … but i want to store that file in different sizes in different destinations. Can you guide me how to do it .. i tried with different ways but i didnt get solution. by this article i can add files in different destinations but i dont know how to resize it.. could you explain it.. thanks in advance .

      • samsonasik said, on August 16, 2013 at 7:32 pm

        you can resize with third party library, i like phpthumbnailer for its need.

      • Krishna said, on August 19, 2013 at 1:36 pm

        Thanks for your reply.. i have one more doubt that … i want to store original image as well as rename image in filesystem, here i am using this code but by this i can save either original file or rename file only one at time … but i want to store both the files in single directory .. could you please explain how to solve this

        $files->receive($front_advert_image[‘name’]);
        $ramdom_filename = uniqid();
        $files->addFilter(‘File\Rename’,array(‘target’ => $files->getDestination(‘front_advert_image’).’/’.$ramdom_filename.’.png’,’overwrite’ => true));
        $files->receive($front_advert_image[‘name’]);
        if (!$files->receive()) {
        $messages = $files->getMessages();
        echo implode(“\n”, $messages);
        }

      • samsonasik said, on August 19, 2013 at 7:38 pm

        you can read “copy” function at phpmanual

    • Krishna said, on August 20, 2013 at 12:02 pm

      can you explain little bit more ……………….

  59. Mohammad Nomaan said, on August 20, 2013 at 4:08 pm

    Hi Samsonasik,
    In Edit Action, how can I bind the File Input with the previously uploaded file. Thanks in advance

    • samsonasik said, on August 26, 2013 at 3:32 pm

      it should be not, check the db, if exist, set required to false, and allow_empty to true, and to avoid confusion to user, show file uploaded as link to uploaded file, then user can choose to update the file or not.

  60. umair Amjadmair said, on August 21, 2013 at 10:46 pm

    How to edit means if i wana change the pic than?

    • samsonasik said, on August 31, 2013 at 11:02 pm

      it should be not, check the db, if exist, set required to false, and allow_empty to true, and to avoid confusion to user, show file uploaded as link to uploaded file, then user can choose to update the file or not.

  61. Ragunathan said, on August 28, 2013 at 4:46 pm

    I set the required field using previous field value

  62. bhawani dash said, on August 31, 2013 at 4:50 pm

    i want the output html like this

    Male

    Male

    but when i echo the
    echo $this->formRow($form->get(‘gender’));

    its give me the output

    male

    female

  63. bhawani said, on August 31, 2013 at 10:43 pm

    hi samsonasik,
    i have one question
    $form->add(array(
    ‘type’ => ‘Zend\Form\Element\Radio’,
    ‘name’ => ‘gender’
    ‘options’ => array(
    ‘label’ => ‘What is your gender ?’,
    ‘value_options’ => array(
    ‘0’ => ‘Female’,
    ‘1’ => ‘Male’,
    ),
    )
    ));

    when i print this command echo $this->formRow($form->get(‘gender’)); it print the out put
    like this
    “Gender
    Female
    Male

    now i want to the output like below
    “Gender
    Female
    Male

  64. Vimal raj said, on September 24, 2013 at 12:02 am

    Dear sam,

    Your post’s are very useful to me, can u help me in following problem ?

    While validation i am getting this error : File ” was not uploaded

    MY $data array

    Array
    (
    [id_school] => 1
    [submit] => Build my school
    [Broucher] => Array
    (
    [name] => triggers_and_procedures.txt
    [type] => text/plain
    [tmp_name] => G:\xampp\tmp\php536A.tmp
    [error] => 0
    [size] => 670
    )

    )

    and in my action

    if($data[‘Broucher’][‘size’] > 0){
    $size = new Size(array(‘max’=>5*(1024*1024)));
    $extension = new \Zend\Validator\File\Extension(array(‘extension’ => array(‘docx’, ‘doc’,’pdf’,’xls’,’txt’)));
    $adapter = new \Zend\File\Transfer\Adapter\Http();
    $adapter->setValidators(array($size,$extension),$data[‘Broucher’][‘name’]);
    if (!$adapter->isValid()){
    $dataError = $adapter->getMessages();
    $error = array();
    foreach($dataError as $key=>$row)
    {
    $broucherError[] = $row;
    }
    }
    }

    After this i am getting above mentioned error in $broucherError

  65. vasanthi said, on September 25, 2013 at 11:48 am

    while uploading my file..i m getting these two error
    Minimum expected size for file is ‘97.66kB’ but ‘107B’ detected

    The given destination is not a directory or does not exist
    how to minimize the size
    $size = new Size(array(‘min’=>1000000));

  66. vasanthi said, on September 25, 2013 at 11:59 am

    if i enter primary value in form textbox then i submit the value that time it display the required dn’t use white space how can i implement that using filter or using jquery help me sir i want restrict the white space in form and at storage level.thanks for communicating with me your comments are really useful.

  67. vasanthi said, on September 25, 2013 at 4:01 pm

    how to upload the file into database

    • samsonasik said, on September 25, 2013 at 4:03 pm

      don’t do that. upload to filesystem, and save only the filename in db

      • vasanthi said, on September 25, 2013 at 4:06 pm

        in assets file r storing but file name is not storing to database,
        i m proceeding with ur article only..

      • samsonasik said, on September 25, 2013 at 4:08 pm

        then just do insert filename into db , as a programmer, you can’t keep asking, you HAVE TO work hard, read the docs from the beginning for how to insert into database. As simple as that

      • vasanthi said, on September 25, 2013 at 4:10 pm

        thanks i will do

    • vasanthi said, on September 26, 2013 at 3:35 pm

      i am entering date format is 25-09-2003 in form that type is “date”.i am using doctrine i give the type=date.if i entering the value 25-09-2013 it’s give error on doctrine.that error is” Fatal error: Call to a member function format() on a non-object in C:\Apache\htdocs\proj\SMBERP\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\DateType.php on line 43″.how can solve that sir pls help.where i change the date format?

  68. vasanthi said, on September 27, 2013 at 8:51 pm

    i am using tabs with in form now i am submit the form at first tab text box fillout the validation is performed from

    second tab because the second tab text box not entered so at submit time the tab is not go to another tab at

    validation area how to go that validation tab at field requiring stage or how to set the focus at the required field.

    help me

    • samsonasik said, on September 28, 2013 at 3:19 pm

      it is javascript area, use javascript! Use js lib like jQuery to easier your life.

      • vasanthi said, on September 28, 2013 at 4:48 pm

        thank you sir

  69. vasanthi said, on October 2, 2013 at 12:34 pm

    hi sam sir now i want your help.i am using single form for two entities and add.phtml also single the contoller also single now how to bind the two entities in controller i am try this type $form->bind($department)->bind($designation);but it’s not work how can do this ?it’s possible are not sir?how to add to tables using single form help me.

    • Ragunathan said, on October 3, 2013 at 9:47 pm

      Using Two Entity This Way $form->bind($value1);$form->bind($value2); U Can Bind Two Values in One Form..But main Question U Can Add One Form Value In Two Table??

  70. Ragunathan said, on October 3, 2013 at 5:24 pm

    My Input Filter Format is public function addInputFilter()
    {
    $inputFilter = new InputFilter\InputFilter();

    // File Input
    $fileInput = new InputFilter\FileInput(‘image-file’);
    $fileInput->setRequired(true);
    $fileInput->getValidatorChain()
    ->attachByName(‘filesize’, array(‘max’ => 20000000));
    //->attachByName(‘fileimagesize’, array(‘maxWidth’ => 100, ‘maxHeight’ => 100))
    //->attachByName(‘filemimetype’, array(‘mimeType’ => ‘image/png,image/x-png, image/jpeg,image/JPG’));
    // $fileInput->getFilterChain( array(
    // ‘target’ => ‘./public/data’,
    // ‘randomize’ => false,
    // ));

    $fileInput->getFilterChain()->attachByName(
    ‘filerenameupload’,
    array(
    ‘target’ => $this->_dir,
    ‘randomize’ => false,
    ‘use_upload_name’ => true,
    ‘overwrite’ => true,
    ‘use_upload_extension’ => true,

    )
    );
    $inputFilter->add($fileInput);

    $this->setInputFilter($inputFilter);
    }
    i Want To Convert This Format To Some think like

    $inputFilter->add($factory->createInput(array(
    ‘name’ => ‘fupload’,
    ‘required’ => true,
    ‘filters’ => array(
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘filesize’,
    ‘options’ => array(
    ‘min’ => 1,
    ‘max’ => 20000000,
    ‘messages’ => array(
    \Zend\Validator\NotEmpty::IS_EMPTY => ‘Code can not be empty.’
    ),),),
    ‘filerenameupload’ => array(
    ‘target’ =>’./public/data’,
    ‘randomize’ => false,
    ‘use_upload_name’ => true,
    ‘overwrite’ => true,
    ‘use_upload_extension’ => true,

    ),
    ),
    )));
    san you give correct syntax

  71. Ragunathan said, on October 3, 2013 at 6:35 pm

    Can U Give Me This Format In My Validation Code..
    I Try This Format But Not Works..
    $inputFilter->add($factory->createInput(array(
    ‘name’ => ‘fupload’,
    ‘required’ => true,
    ‘filters’ => array(
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘filesize’,
    ‘options’ => array(
    ‘min’ => 1,
    ‘max’ => 20000000,
    ‘messages’ => array(
    \Zend\Validator\NotEmpty::IS_EMPTY => ‘Code can not be empty.’
    ),),),
    ‘filerenameupload’ => array(
    ‘target’ =>’./public/data’,
    ‘randomize’ => false,
    ‘use_upload_name’ => true,
    ‘overwrite’ => true,
    ‘use_upload_extension’ => true,

    ),
    ),
    )));

  72. Ragunathan said, on October 3, 2013 at 9:49 pm

    Thank You Sir..i Follow Your Tutorial I Can Insert File In MY File manager and also i insert my data in my database with single form..thank you so much..:)

  73. Bharath said, on October 7, 2013 at 4:53 pm

    i want to set the upload field as non required field can u help me..

  74. Bharath said, on October 7, 2013 at 5:32 pm

    I Try That But its not working..my code is
    $inputFilter->add(
    $factory->createInput(array(
    ‘name’ => ‘Fileupload’,
    ‘required’ => false
    ))
    );
    and alsoi write myvalidation codein my controller

    $size = new Size(array(‘min’=>’0.001MB’,’max’=>’5.0MB’)); //minimum bytes filesize
    $extensionvalidator = new \Zend\Validator\File\Extension(array(‘extension’=>array($_POST[‘fileformat’])));

    $adapter = new \Zend\File\Transfer\Adapter\Http();
    $adapter->setValidators(array($extensionvalidator,$size,$req), $File[‘name’]);
    //$adapter->setValidators(array($size), $File[‘name’]);

    if (!$adapter->isValid())

  75. Bharath said, on October 7, 2013 at 5:48 pm

    I Add ‘allow_empty’ => true in my input filter but still not working
    the code is
    $inputFilter->add(
    $factory->createInput(array(
    ‘name’ => ‘Fileupload’,
    ‘required’ => false,
    ‘allow_empty’ => true
    ))
    );
    i think problem is here

    $adapter = new \Zend\File\Transfer\Adapter\Http();
    $adapter->setValidators(array($extensionvalidator,$size,$req), $File[‘name’]);
    //$adapter->setValidators(array($size), $File[‘name’]);

    if (!$adapter->isValid())

    • samsonasik said, on October 7, 2013 at 6:37 pm

      i think yes, add if (!empty($File[‘name’])) to check before that 🙂

  76. Bharath said, on October 7, 2013 at 7:13 pm

    Thanks Thanks a lot..its working…:)

  77. priyank said, on October 18, 2013 at 8:54 pm

    i need your database please help me…

  78. viraj said, on October 29, 2013 at 4:29 pm

    Not working for me. It’s give an error “File not found” when i writer $file[‘name’] and when i write $file[‘tmp_name’] it show an error like “file is not uploaded” and above all it’s not add in my database
    here i giving my code.

    controller addAction.

    public function addAction()
    {
    $dbAdapter = $this->getServiceLocator()->get(‘Zend\Db\Adapter\Adapter’);
    $form = new SiteUserForm($dbAdapter);
    $form->get(‘submit’)->setValue(‘Add’);
    $request = $this->getRequest();
    if ($request->isPost()) {
    $nonFile = $request->getPost()->toArray();
    $file = $this->params()->fromFiles(“vImage”);
    $data = array_merge($nonFile, array(“vImage” => $file[‘tmp_name’]));
    $user = new SiteUser();
    $form->setData($data);
    $form->setInputFilter($user->getInputFilter());
    if ($form->isValid()) {
    $user->exchangeArray($data);
    $this->getSiteUserTable()->saveUser($user);

    // Redirect to list of albums
    return $this->redirect()->toRoute(‘user’);
    }
    }
    return array(‘form’ => $form);
    }

    model

    public function exchangeArray($data)
    {

    $this->vImage = (!empty($data[‘vImage’]))? $data[‘vImage’]:null;
    $this->vAddress1 = (!empty($data[‘vAddress1’]))? $data[‘vAddress1’]:null;

    }

    I have not added any filter for image field.

    so, please help me out to solve this issue.

  79. Ahmed Sliman said, on November 18, 2013 at 3:18 pm

    Welcome sir,

    I apply the example in a module i program now, I want to upload two files, The first upload right but the second give me an error message “File ‘021317.png’ was illegally uploaded. This could be a possible attack”

  80. Ahmed Sliman said, on November 19, 2013 at 4:06 pm

    Thanks sir.

  81. nilesh said, on November 27, 2013 at 2:57 pm

    how to upload an image and video without creating a form? means directly open a box for selecting a file on click of text(upload image)

  82. Isaac said, on December 27, 2013 at 3:03 am

    Hi! Thanks for your Posts,
    I have a dude, How Can I Save It in a Different Module?
    Ex.
    Module Application/src/Application/Images->Save Here.

    And

    how can show the image in a different Module?..

    Module Shows/Index-> Show Here.

    It´s only images what i want to show but i suposs that this is with \Zend\File\Transfer\Adapter\Http();, But How?
    Can You Give The Code Example.

    • samsonasik said, on December 27, 2013 at 11:29 pm

      since you’re using ZendSkeletonApplication, then your directory index is your application, so you should can got it by do :

      $adapter->setDestination('./module/Application/src/Application/Images');
      
  83. Isaac said, on January 3, 2014 at 10:58 pm

    Can You Show Me The Right Form To Show The Image, and the edit action for the file input element.

    Pleas.

  84. Isaac said, on January 4, 2014 at 12:36 am

    Can you do a post about how to create a CRUD with relationship tables in ZF2 and a field called image like this post and show it in the edit action, because i know that need diferents model and i dont know how to show in the edit action the data.

    Please help me, please.

  85. Gonzalo said, on January 21, 2014 at 9:38 am

    What do you think with this solution without the adapter:
    if ($request->isPost()) {
    $campaign = new Campaign();
    $sm = $this->getServiceLocator();
    $campaign->setServiceLocator($sm);

    $File = $request->getFiles()->toArray();

    $config = $this->getServiceLocator()->get(‘config’);

    $destination = $config[‘path_img’][‘campaign_main_img’];

    $filter = new Rename(array(
    “target” => $destination.$File[‘path_main_image’][‘name’],
    “randomize” => true,
    ));

    $File[‘path_main_image’] = $filter->filter($File[‘path_main_image’]);

    $post = array_merge_recursive(
    $request->getPost()->toArray(),
    $File
    );

    $form->setData($post);

    if ($form->isValid()) {

    $campaign->exchangeArray($form->getData());

    $this->getCampaignTable()->saveCampaign($campaign);

    return $this->redirect()->toRoute(‘campaign’, array(‘action’ => ‘list’));
    }
    }

    Regards!

  86. Mohammad Nomaan Patel said, on February 10, 2014 at 5:35 pm

    Hi Samsonasik,
    I would like to ask a question. In my registration form profile pic is not a mandatory field. If a user doesn’t select an image file, i would like to upload or set the mapping for a default file for it. For example as in facebook a default profile pic is displayed if no profile pic is set.
    Any help would be appreciated….

    • samsonasik said, on February 11, 2014 at 12:16 am

      add ‘required’ => false and/or ‘allow_empty’ => true.

  87. therapist cobham said, on February 20, 2014 at 4:05 am

    I can’t have enough of it.

  88. angel said, on March 6, 2014 at 11:13 pm

    file Upload progress Bar help me friends

  89. cany said, on March 11, 2014 at 5:17 pm

    hello , i am getting this error
    Zend\Mvc\Router\Exception\RuntimeException

    File:

    D:\Program Files\ZendServer\data\libraries\Zend_Framework_2\2.2.1\library\Zend\Mvc\Router\Http\TreeRouteStack.php:313

    Message:

    Route with name “fileUpload” not found

    • samsonasik said, on March 11, 2014 at 7:55 pm

      read the error :p, you need to define “fileUpload” route 😛

  90. Azhar Ahmad said, on April 3, 2014 at 5:07 pm

    when i run this code in my project it showing me the following error
    Call to undefined method getRequest()

    what should i do??

  91. Azhar Ahmad said, on April 4, 2014 at 11:20 am

    i use $this-> getRequest() but it showing me the same error

    • samsonasik said, on April 4, 2014 at 1:34 pm

      you need to start with skeleton app, and debug it, please do effort!

      • Azhar Ahmad said, on April 4, 2014 at 7:38 pm

        i started the skeleton app but found the same problem and i am using my own mvc not zend mvc.

        and how can i destroy the session using zend session 2.3

  92. Zsolt said, on April 8, 2014 at 9:06 pm

    Your code helped me. Thank you very much!

  93. Fabian Wüthrich said, on April 25, 2014 at 7:11 pm

    You should use “type” in the parent array not in the attribute array. In this way Zend recognize the form element correct (with enctype usw. see http://framework.zend.com/manual/2.3/en/modules/zend.form.file-upload.html#the-form-and-inputfilter)

    $this->add(array(
    ‘name’ => ‘fileupload’,
    ‘type’ => ‘file’,
    ‘options’ => array(
    ‘label’ => ‘File Upload’,
    ),
    ));

  94. Azhar Ahmad said, on May 8, 2014 at 2:07 pm

    How can i validate the type of file and its size????

  95. alban said, on May 8, 2014 at 2:28 pm

    Come on Samsonik, you are a good one with zf, but let me say that writing such a log of code it is not a simple file upload, that normally would take just 10 line of code in pure php.

  96. sistema said, on May 30, 2014 at 12:27 am

    how can you validate https://github.com/doctrine/DoctrineModule/blob/master/docs/validator.md ?

  97. aguscandraharahap said, on August 5, 2014 at 6:21 pm

    bagaimana kalau kita mengupload file dengan database..?
    terima kasih mas..

    • samsonasik said, on August 5, 2014 at 8:50 pm

      file nya upload ke drive folder, namanya simpan di database.

      • aguscandraharahap said, on August 6, 2014 at 3:02 pm

        dibuat pada controllernya mas..
        kira2 perintahnya gimana mas?
        terima kasih mas..

  98. aguscandraharahap said, on August 6, 2014 at 3:12 pm

    hmm..
    ada gag mas tutorialnya yang menyimpannya didatabase terus nanti ketika kita mau lihat gambarnya muncul mas..?
    maaf mas, banyak tanya..
    terima kasih mas..

  99. Denis said, on August 9, 2014 at 11:43 pm

    Hi, Sam!
    I have the same problem as Vimal raj.

    While validation i am getting this error : File ‘C:\xampp\tmp\php97DD.tmp’ could not be renamed. An error occurred while processing the file.

    This is my Filter class.

    $this->add(array(
    ‘name’ => ‘fileupload’,
    ‘required’ => true,
    ‘filters’ => array(
    array(‘name’ => ‘\File\Rename’,
    ‘options’ => array(
    ‘source’ => ‘*’,
    ‘target’ => ‘/../../../../../public/img/photo.jpg’,
    ‘overwrite’ => true,
    ‘randomize’ => true,
    ),
    ),
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘\File\Size’,
    ‘options’ => array(
    ‘max’ => ’20Mb’,
    ),
    ),
    array(
    ‘name’ => ‘\File\Extension’,
    ‘options’ => array(
    ‘extension’ => ‘jpg,gif,png’,
    ),
    ),
    ),
    ));

    Could you help me with it?

  100. Denis said, on August 10, 2014 at 12:12 am

    I check this http://eliteinformatiker.de/2011/09/02/thumbnails-upload-and-resize-images-with-zend_form_element_file/

    I use filter in my Constructor Class, not in Filter. Now I don’t understand how get new filename (renamed).

  101. Mat L said, on August 31, 2014 at 3:43 pm

    Hello Samsonasik,

    First of all, thank you.
    I’m learning ZF2 and you helped me a lot (realy a lot).

    My project will soon be released, but I still have a problem with my images upload.
    Upload is working fine but I don’t understand how I can reduce quality of JPG/PNG (idealy) before upload.
    Any tips plz?

    Kind regards,
    Mat’

  102. reema said, on September 23, 2014 at 2:50 pm

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

    $project = new Projects();

    $nonFile = $request->getPost()->toArray();
    $File = $this->params()->fromFiles(‘imageupload’);
    $adapter = new \Zend\File\Transfer\Adapter\Http();

    $data = array_merge(
    $nonFile,
    array(‘imageupload’=> $File[‘name’])
    );

    $form->setData($data);

    if ($form->isValid()) {

    $size = new Size(array(‘min’=>2000)); //minimum bytes filesize

    $adapter->setValidators(array($size), $File[‘name’]);
    if (!$adapter->isValid()){
    $dataError = $adapter->getMessages();
    $error = array();
    foreach($dataError as $key=>$row)
    {
    $error[] = $row;
    }
    $form->setMessages(array(‘imageupload’=>$error ));
    } else {
    $name=$project->name;
    $newFile=’/’.$name.’.jpeg’;
    $adapter->setDestination(‘module/Project/photo/’);

    $adapter->addFilter(‘File\Rename’,
    array(‘target’ => $adapter->getDestination().’/’.$newFile,
    ‘overwrite’ => true));

    if ($adapter->receive($File[‘name’])) {

    $file = $adapter->getFilter(‘File\Rename’)->getFile();
    print_r($file[0][‘target’]);
    }

    }
    }
    }
    i am unable to rename the file and save it in database without renaming im able to store as well as i folder.

    • samsonasik said, on September 24, 2014 at 12:14 am

      you probably surplus the “/” after getDestination() because already in the newFile definition.

  103. Nomaan said, on September 23, 2014 at 4:20 pm

    Hi Samsonasik,

    Your tutorial worked perfectly for me but I’m stuck while display the images which are uploaded in data folder as I’m saving the images in data folder. I’m using virtual host which points to public folder. Please refer to the virtual host script

    ServerAdmin admin@beatsboom
    ServerName zf2-tutorial
    DocumentRoot “E:\Nomaan\zf2_projects\zf2-tutorial\public”
    ServerAlias http://www.zf2-tutorial
    SetEnv APPLICATION_ENV “development”
    ErrorLog “logs/zf2-tutorial-error.speck-error.log”
    CustomLog “logs/zf2-tutorial-logs.speck-logs.log” common

    DirectoryIndex index.php
    AllowOverride All
    Order allow,deny
    Allow from all

    Waiting for your reply & thanks in advance.

    • samsonasik said, on September 24, 2014 at 12:16 am

      all asset will be relative to root folder of your app, so you should can call file_get_contents(“./data/file.ext’); , use header to set specific content type.

  104. Gastón Cortés said, on October 26, 2014 at 7:43 am

    Thank you! Samsonasik for this post.

  105. Ashim said, on December 4, 2014 at 8:08 pm

    Hi Abdul Malik,

    I saw your all the post but you never tried to implement blueimp with zf2. Actually I am trying to implement jQuery File Upload (blueimp) with zend framework 2.

    I put all the js and css files inside public folder and trying to upload the files inside public folder. But unfortunately when I submit the Start upload button its giving below error

    SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

    But my browser and server supports json, I have tested.

    Its running fine when test for jQuery File Upload (blueimp) demo on my local server.

    Please help me if you have any idea.

    Any sample code or any help is fine.
    Thanks in advance.

  106. Jara said, on December 14, 2014 at 7:26 pm

    Dear Samsonasik,
    Thank you so much for your wonderful tutorials! I have a problem. I have created an upload form with some other fields. When I click ‘Add’ the file name is sent to database and the file is saved in a file system. I also need to edit the fields. When I click the ‘Edit’ link, all the fields are filled but File upload field becomes empty. Could you please explain how to bring the uploaded file in an Edit form?

    • samsonasik said, on December 14, 2014 at 8:24 pm

      you should not fill upload field when do edit, change with existing data with ( image / link ) so you can decide to re-upload or make it empty.

  107. Jara said, on December 19, 2014 at 10:23 pm

    Thank you for your reply. Still I am not clear yet. In this example, you have profile name and file upload. Suppose, you give a profile name and upload a file. Later, you need to change the profile name. When you click edit, change profile name and click upload now. Now, the the file upload becomes empty. My question is how to keep the uploaded file when we edit the profile name?? How to delete a file from a file system when an entry is deleted. Coding would be really helpful.

  108. youssef said, on February 21, 2015 at 4:22 am

    Chokrabe Akhii 7ayaaka llaah

  109. tkjsmknasionalpadang said, on March 6, 2015 at 10:48 am

    Bagaimana kalau kita mau buat multiple upload y mas..? Pada bagian mana yang harus ditambahkan..?

  110. aicha said, on March 12, 2015 at 11:23 pm

    thank you very much for this tutorial, I follow it step by step, but I don’t know what is wrong!! the name of the file didn’t save in the database and also the file didn’t save in the folder system. any error was displayed!!!pleaise help

  111. chedi said, on April 28, 2015 at 6:29 am

    thanks for this tutorial , i have question …. how i can’t do messaging with zend framwork and thanks so match

  112. Akbar Adeeb said, on May 14, 2015 at 7:43 pm

    Hey bro can you tell me how to implement clint side validaton in a zend framework application

    • samsonasik said, on May 15, 2015 at 5:03 am

      client side validation is nothing to do with zf, do javascript instead

  113. Akbar Adeeb said, on May 15, 2015 at 12:09 pm

    THnaks bro

  114. iverzak said, on July 13, 2015 at 9:01 pm

    Hello samsonasik , thanks for the tutorial , am facing an issue in my application , when i sumbit the upload form i lost the $file name so i couldn’t add my picture name to my database this is my cose :

    my add action in AlbumController.php :

    public function addAction()
    {
    $form = new AlbumForm();
    $form->get(‘submit’)->setValue(‘Add’);

    $request = $this->getRequest();
    if ($request->isPost())
    {
    $album = new Album();
    $form->setInputFilter($album->getInputFilter());
    $form->setData($request->getPost());

    if ($form->isValid())
    {
    $album->exchangeArray($form->getData());
    $this->getAlbumTable()->saveAlbum($album);

    // Redirect to list of albums
    return $this->redirect()->toRoute(‘album’);
    }
    }
    return array(‘form’ => $form);
    }

    AlbumForm.php

    $this->add(array(
    ‘name’ => ‘photo’,
    ‘type’ => ‘file’,
    ‘options’ => array(
    ‘label’ => ‘File Upload’,
    ),
    ));

    Album.php

    $inputFilter->add(
    $factory->createInput(array(
    ‘name’ => ‘photo’,
    ‘required’ => true,
    ))
    );

    the line that i use to get form in my add.phtml:

    echo $this->formRow($form->get(‘photo’));

    any help or suggestion please;

    • iverzak said, on July 14, 2015 at 2:04 am

      Hello , problem fixed , thank you any way

  115. naaloonenu said, on November 19, 2015 at 2:56 pm

    hi. Thanks for awsome tutorial.
    I am not able to uplad files to network folder in server. it would be great if you can helpme with uploading files to network folder. Thank you

  116. danleyb2 said, on January 31, 2016 at 1:59 pm

    Reblogged this on danleyb2.

  117. Danny Nguyen said, on March 2, 2016 at 6:28 pm

    When I call new \Zend\File\Transfer\Adapter\Http(), I see a bug from the __construct function. You can see the detail of this bug in this image: http://prntscr.com/aa7hyj . I’m using Zend Framework version 2.4.2.

    • samsonasik said, on March 2, 2016 at 7:20 pm

      “fileupload” is just an element name, the source of error is not there, please do effort!

  118. salman said, on March 4, 2016 at 5:41 pm

    how i can delete a file using zend framework plz anyone can tell

  119. Sergei Vakulenko said, on June 20, 2016 at 10:26 pm

    How can I do that in Zend Expressive?

  120. Muhammad M.Nasir said, on August 17, 2016 at 8:31 pm

    I am following all your posts and really thez are great to learn ZF2 , but I have stopped here to push a question :

    I want to inject this upload way in an exist module , I have tried but 😦 .. so I guess my problem is in this file :

    zend\module\Pizza\src\Pizza\Controller\PizzaController.php

    public function addAction()
    {
    $add_form = new AddPizzaForm();
    $request = $this->getRequest();
    if($request->isPost())
    {
    $pizza = new Pizza();
    $add_form->setInputFilter($pizza->getInputFilter());

    // upload photo project
    $nonFile = $request->getPost()->toArray();
    $File = $this->params()->fromFiles(‘fileupload’);
    $datammn = array_merge(
    $nonFile, //POST
    array(‘fileupload’=> $File[‘name’]) //FILE…
    );
    //end for the upload photo project

    $add_form->setData($request->getPost());

    //set data post and file …

    if($add_form->isValid())
    {

    // upload photo project
    $size = new Size(array(‘min’=>2000000)); //minimum bytes filesize
    $adapter = new \Zend\File\Transfer\Adapter\Http();
    //validator can be more than one…
    $adapter->setValidators(array($size), $File[‘name’]);

    if (!$adapter->isValid()){
    $dataError = $adapter->getMessages();
    $error = array();
    foreach($dataError as $key=>$row)
    {
    $error[] = $row;
    } //set formElementErrors
    $add_form->setMessages(array(‘fileupload’=>$error ));
    } else {
    $adapter->setDestination(‘./public/mmn’);
    if ($adapter->receive($File[‘name’])) {
    //$pizza->exchangeArray($add_form->getData());

    //$this->getPizzaTable()->save($pizza);
    $add_form->setData($datammn);
    //echo ‘Profile Name ‘.$pizza->profilename.’ upload ‘.$pizza->fileupload;
    }
    }
    //end for the upload photo project
    $pizza->exchangeArray($add_form->getData());
    $this->getPizzaTable()->save($pizza);

    }
    return $this->redirect()->toRoute(‘pizza’,array(‘action’=>’nasir’));
    }
    return array(‘form’ => $add_form);

    }

    is it possible to advice me 🙂 thanks a lot ..

  121. nubicus said, on September 4, 2016 at 12:38 am

    // kalau ini kenapa ya mas, tidak bisa $adapter->receive?

    $adapter->setDestination(PUBLIC_PATH.’/img/logo’); // .. /public/img/logo
    $adapter->receive($files[‘image-file’]);

    ketika saya print_r($adapter->getFileInfo());

    [image-file] => Array
    (
    [name] => Screenshot from 2016-08-31 13:55:33.png
    [type] => image/png
    [tmp_name] => /tmp/phpEE3Y5g
    [error] => 0
    [size] => 176447
    [options] => Array
    (
    [ignoreNoFile] =>
    [useByteString] => 1
    [magicFile] =>
    [detectInfos] => 1
    )

    [validated] => 1
    // receive ?
    [received] =>
    [filtered] =>
    [validators] => Array
    (
    [0] => Zend\Validator\File\Upload
    )

    [destination] => ../public/img/logo
    )

    mohon bimbingannya..
    terima kasih..

    • samsonasik said, on September 7, 2016 at 3:32 pm

      coba set PUBLIC_PATH constant di public/index.php dengan absolute path ( dengan realpath(getcwd()))

  122. Febry Damatraseta Fairuz said, on September 8, 2016 at 9:58 am

    your code is awesome, but i tried to follow your instruction every single step. why my file not want to switch to a predetermined place..?
    return of $adapter->receive($File[‘name’]) always false. can you tell me

    • samsonasik said, on September 8, 2016 at 7:19 pm

      debug if folder as:

      realpath(dirname(__DIR__).'/assets');
      

      exists and writable.

  123. sathishkumarssk said, on January 11, 2017 at 2:28 pm

    How to store images in database using above program??

  124. Miloš Đorić said, on January 29, 2017 at 6:24 pm

    Using ZF3. After submiting file, constantly get: Fatal error: Class ‘Fantasy\Controller\Http’ not found error.

    • samsonasik said, on January 29, 2017 at 9:41 pm

      I guess you’re using new Http() directly in the class, make sure you add use statement :

      “`php
      use Zend\File\Transfer\Adapter\Http;
      “`

      or do direct with backslash prefix:

      “`php
      new \Zend\File\Transfer\Adapter\Http();
      “`

      If you don’t have the class in your vendor, make sure to require it via composer:

      “`bash
      composer require zendframework/zend-file
      “`

      • sri said, on February 5, 2017 at 2:15 am

        Hi samsonasik,

        I have two doubt,

        The first one, I am using zend framework, I want confirm dialog box before user submit. If i use normal confirm box, it is not responding properly. please refer the below code…give solution.

        <form action="form->getAction() ?>” method=”form->getMethod() ?>” class=”stdform stdform2″ id=”cash”>
        form->employee_id ?>
        form->ename ?>
        ……………….

        $(document).ready(function(){
        $(‘#cash’).form2json({success: function() {
        location.href=”/donatecash/index”;
        }
        });
        });

        the second one is please refer below url.

        http://stackoverflow.com/questions/42043094/datatables-warning-json-data-from-server-could-not-be-parsed-this-is-a-caused

        please give any solution for this problems………Thank you

      • samsonasik said, on February 5, 2017 at 8:38 am

        in zf1, you can disable layout and disable view rendering if it only needs a json, something like:

        $this->getHelper('layout')->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();
        

        before echoing the json in action.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: