Colección ZF2 FileUpload

No puedo hacer funcionar mi colección de archivos. Esto es lo que he hecho:

https://gist.github.com/manuakasam/1ac71daf7269616f55f0

Básicamente, $request->getFiles() contiene la información adecuada. Así que la carga a PHP en sí funciona. Pero una vez que el InputFilter ejecuta los datos, todo se pierde. Apprently FileRenameUpload hace algo sospechoso y no puedo averiguar qué es exactamente. Todo lo que sé es que mis datos se pierden …

Los permisos de escritura no son el problema. Estoy probando esto actualmente en mi devbox en Windows a través de PHP 5.5 CLI

Parece que el problema es la Colección de Elementos . En el pasado, solo se admitía que los Fieldsets estuvieran en una Colección. Tal vez el soporte de Element se agregue más tarde, pero estoy bastante seguro de que está defectuoso y por lo tanto no funciona para usted de esta manera. Reformé su código para usar Fieldsets y lo validé y los archivos cargados se renombraron y movieron correctamente. El problema estaba dentro de CollectionInputFilter, que parece que uno no está correctamente actualizado para admitir la colección de elementos.

Probablemente obvio: asegúrese de preparar la colección antes de la validación.

Aquí está mi bifurcación modificada de su código: https://gist.github.com/netiul/efaf8bd4545d216fd26c

Controlador

 public function indexAction() { $request = $this->getRequest(); if($request->isPost()) { $post = array_merge_recursive( $request->getPost()->toArray(), $request->getFiles()->toArray() ); $this->incidentForm->prepare(); $this->incidentForm->setData($post); if($this->incidentForm->isValid()) { \Zend\Debug\Debug::dump($this->incidentForm->getData()); die(); } } return [ 'form' => $this->incidentForm ]; } 

TheFilter (no cambiado, bueno un pequeño cambio)

  $singleFileFilter = new InputFilter(); $singleFileFilter->add( [ 'name' => 'attachment', 'required' => false, 'filters' => [ [ 'name' => 'filerenameupload', 'options' => [ 'target' => 'data/incident_attachments/', /* small change here, removed the slash in front of data to make the path relative */ 'randomize' => true, 'use_upload_name' => false, 'overwrite' => false ] ] ] ] ); $attachedFilesFilter = new CollectionInputFilter(); $attachedFilesFilter->setInputFilter($singleFileFilter); $this->add($attachedFilesFilter, 'attachedFiles'); 

La forma

  $this->setAttribute('enctype', "multipart/form-data"); $fileElement = new Form\Element\File('attachment'); $fileElement->setOptions( [ 'label' => 'Add Attachment', 'label_attributes' => [ 'class' => 'control-label col-sm-3' ] ] ); $fileElement->setAttributes([ 'class' => 'form-control' ]); $collectionTarget = new Form\Fieldset('uploadItem'); $collectionTarget->add($fileElement); $this->add( [ 'name' => 'attachedFiles', 'type' => 'collection', 'options' => [ 'count' => 3, 'target_element' => $collectionTarget ] ] ); 

Salida después de la validación

 array (size=1) 'attachedFiles' => array (size=3) 0 => array (size=1) 'attachment' => array (size=5) 'name' => string '1326459.png' (length=11) 'type' => string 'image/png' (length=9) 'tmp_name' => string 'data/incident_attachments_538c30fe0fb2f' (length=39) 'error' => int 0 'size' => int 791802 1 => array (size=1) 'attachment' => array (size=5) 'name' => string '1510364_10152488321303345_257207784_n.jpg' (length=41) 'type' => string 'image/jpeg' (length=10) 'tmp_name' => string 'data/incident_attachments_538c30fec55c4' (length=39) 'error' => int 0 'size' => int 53272 2 => array (size=1) 'attachment' => array (size=5) 'name' => string 'IMG_20140430_095013.jpg' (length=23) 'type' => string 'image/jpeg' (length=10) 'tmp_name' => string 'data/incident_attachments_538c30ff4489d' (length=39) 'error' => int 0 'size' => int 1039118 

La forma en que validé archivos en ZF2

en composer.json

  "imagine/Imagine": "0.3.*", 

en tu control

 use Zend\Validatior\File\Size; use Imagine\Gd\Imagine; use Imagine\Image\Box; use Imagine\Image\Point; public function imageAction() { $id = ( int ) $this->params ()->fromRoute ( 'id', 0 ); if (! $id) { return $this->redirect ()->toRoute ( 'newscategory' ); } $form = new YourForm(); $form->get ( 'link_id' )->setAttribute ( 'value', $id ); $request = $this->getRequest(); if ($request->isPost()) { // Make certain to merge the files info! $image = new Entityimage(); $form->setInputFilter($image->getInputFilter()); $post = array_merge_recursive( $request->getPost()->toArray(), $request->getFiles()->toArray() ); $form->setData($post); if ($form->isValid()) { $size = new \Zend\Validator\File\ImageSize(array( 'minWidth' => 30, 'minHeight' => 30, 'maxWidth' => 1024, 'maxHeight' => 920, )); //minimum bytes filesize $isImage = new \Zend\Validator\File\IsImage(); $mimeType = new \Zend\Validator\File\MimeType(array('image/gif', 'image/jpg','image/jpeg','image/png','enableHeaderCheck' => true)); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size), $post['fileupload']['name']); $adapter->setValidators(array($isImage), $post['fileupload']['name']); $adapter->setValidators(array($mimeType), $post['fileupload']['name']); if (!$adapter->isValid()){ $dataError = $adapter->getMessages(); $error = array(); foreach($dataError as $key=>$row) { $error[] = $row; } $form->setMessages(array('fileupload'=>$error )); $messages = $form->getMessages(); return $this->redirect ()->toRoute ( 'your route' ); // print_r($messages);die('file errors'); } else { $adapter->setDestination('images/yourdir'); if ($adapter->receive($post['fileupload']['name'])) { $image->exchangeArray($form->getData()); switch(strtolower($_FILES['fileupload']['type'])) { case 'image/jpeg': $filename = imagecreatefromjpeg('images/yourdir/'.$post['fileupload']['name']); break; case 'image/png': $filename = imagecreatefrompng('images/yourdir/'.$post['fileupload']['name']); break; case 'image/gif': $filename = imagecreatefromgif('images/yourdir/'.$post['fileupload']['name']); break; default: exit('Unsupported type: '.$_FILES['fileupload']['type']); } ob_start(); imagejpeg($filename); // large image $large = base64_encode(ob_get_contents()); // returns output $mainimgWidth = imagesx($filename); $mainimgHeight = imagesy($filename); $thumbWidth = 48; //intval($mainimgWidth / 4); $thumbHeight = floor( $mainimgHeight * ( $thumbWidth / $mainimgWidth ) ); //intval($mainimgHeight / 4); $new = imagecreatetruecolor($thumbWidth, $thumbHeight); $backgroundColor = imagecolorallocate($new, 255, 255, 255); imagefill($new, 0, 0, $backgroundColor); imagecopyresampled($new, $filename, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainimgWidth, $mainimgHeight); /** Catch the imagedata */ ob_start(); imagejpeg($new); $data = ob_get_clean(); // Destroy resources imagedestroy($filename); imagedestroy($new); // Set new content-type and status code $thumb = base64_encode($data); // imagine library was intsalled by the composer in the test server by amarjit ob_end_clean(); $imagine = new Imagine(); //rename files $filedata = array( 'id' => $post ['id'], 'news_link_id' => $post ['news_link_id'], 'alt' => $post ['alt'], 'detail' => $post ['detail'], 'active' => $post ['active'], 'thumb' => $thumb, 'large' => $large, 'created' => date('Ymd H:i:s'), 'createdby' => 1, ); $id = $this->getImageTable ()->save ( $filedata ); $imagine->open('images/yourdir/'.$post['fileupload']['name']) ->save('images/yourdir/filename-'.$id.'.jpg'); /** * delete the origional uploaded file; */ unlink('images/yourdir/'.$post['fileupload']['name']); return $this->redirect ()->toRoute ( 'newscategory' ); } } }else{ $messages = $form->getMessages(); } } return array ( 'id' => $id, 'form' => $form, ); }