Zend_Form_Element_File to rename file saving extension

Oleg picture Oleg · Mar 8, 2011 · Viewed 8.9k times · Source

I use Zend Form and upload file. I need to rename and user addFilter for it. But if I try to get extension of the file as in the code I get an error "Too much files, maximum '1' are allowed but '2' are given". If I try to get extension using $_FILES it looks like it can work out but it seems ugly. Could you please tell me how to rename file saving it's extension?

        $form = new Form_ImportSubscribers();               
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                //it looks like it works but it's ugly solution
//              $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); 
                //causes an error "Too much files, maximum '1' are allowed but '2' are given"           
                $extension = pathinfo($form->file->getFileName(), PATHINFO_EXTENSION);              
                $form->file->addFilter('Rename', $accountId . '_' . time() .  '.' . $extension);

                if (!$form->file->receive()) {
                    $this->view->form = $form;
                    $this->view->listName = $list->list_name;                                   
                    return;
                }       

Answer

Marcin picture Marcin · Mar 8, 2011

I assume that you upload multiple files if $form->file->getFileName() returns more than one value. In this case you could apply Rename filter and receive individual files as follows:

/*@var $adapter Zend_File_Transfer_Adapter_Http */
$adapter =  $form->file->getTransferAdapter();
$receivingOK = true; 
foreach ($adapter->getFileInfo() as $file => $info) {                                     
    $extension = pathinfo($info['name'], PATHINFO_EXTENSION); 
    $adapter->addFilter('Rename', $accountId . '_' . time() .  '.' . $extension, $file);
    if (!$adapter->receive($file)) {
         $receivingOK = false;
    }
}

if (!$receivingOK) {
    $this->view->form = $form;
    $this->view->listName = $list->list_name;                                   
    return;
} 

It should also work even if you don't perform multiple files upload.