ZF2 FileUpload Collection

女生的网名这么多〃 提交于 2019-12-04 11:07:55

问题


I am unable to get my fileupload collection to work. This is what I've done:

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

Basically the $request->getFiles() contains the proper information. So the upload to PHP itself works. But once the InputFilter runs over the data, it all gets lost. Apprently FileRenameUpload does something fishy and I can't figure out what exactly. All I know is my data gets lost...

Write permissions are not the problem. I'm testing this currently on my devbox on windows via PHP 5.5 CLI


回答1:


Looks like the problem is the Collection of Elements. In the past only Fieldsets were supported to be in a Collection. Maybe Element support is added later, but I'm pretty sure it's buggy and therefore not working for you in this way. I reworked your code to be using Fieldsets and I got it validated and the uploaded files properly renamed and moved. The problem was inside the CollectionInputFilter, that one doesn't seem to be correctly updated to support collection of Elements.

Probably obvious: make sure to prepare the collection before validation.

Here's my modified fork of your code: https://gist.github.com/netiul/efaf8bd4545d216fd26c

Controller

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 (not changed, well a small change)

    $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');

TheForm

    $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
            ]
        ]
    );

Output after validation

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



回答2:


The way i validated files in ZF2

in composer.json

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

in your controller

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('Y-m-d 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,

        );
    }


来源:https://stackoverflow.com/questions/23953525/zf2-fileupload-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!