inputfilter for fileupload,基本用法

时间:2017-07-10 18:05:21

标签: validation zend-framework zend-framework3

现在我对这个ZF3的内容有了更多的了解。我可以(在一些帮助下)实现我想要的几乎所有东西。为了我的新版本,我开发了一个测试项目。

有些问题仍然没有答案,我找不到可用的解释。

我的新问题是InputFilterAwareInterface。我尝试了教程中的字符串示例,到目前为止一切正常。但是就像你总能找到一切容易的主题一样,如果你走得更远就会突然结束。

我需要一个用于xls和xlsx文件的Inputfilter。我当然用谷歌搜索,阅读教程,在zend教程中搜索,因为我有想法必须在某处存在一些完整的参考,但我无法找到任何。

所以我尝试了这个:

    $inputFilter->add([
                'type'     => 'Zend\InputFilter\FileInput',
                'name'     => 'DCL_Path',
                'required' => true,
                'validators' => [
                        ['name'    => 'FileUploadFile'],
                        [
                                'name'    => 'FileMimeType',
                                'options' => [
                                        'mimeType'  => ['text/xls', 'text/xlsx']
                                ]
                        ],
                        [
                                'name'    => 'Filesize',
                                'options' => [
                                        'max' => 4096
                                ]
                        ],
                ],
//              'filters'  => [
//                      [
//                              'name' => 'FileRenameUpload',
//                              'options' => [
//                                      'target'=>'./data/upload',
//                                      'useUploadName'=>true,
//                                      'useUploadExtension'=>true,
//                                      'overwrite'=>true,
//                                      'randomize'=>false
//                              ]
//                      ]
//              ],
        ]); 

如你所见,我仍然在与验证器部分作斗争。什么是正确的语法来验证最大大小为4 MB的xls和xlsx文件?

在那之后,对于filterarea来说,我在控制器操作中做了以下操作,因为我曾经习惯

if ($form->isValid()) {
                    $data = $form->getData();
                    // Upload path
                    $location = "public/files/";
                    // A bit validation of uploaded file
                    $allowedExtension = array('xls', 'xlsx');
                    $extension = explode('.', $data['DCL_Path']['name']);
                    $extension = end($extension);
                    //$import['DCL_Path']=$data['DCL_Path']['name'];
                    //$fileName = time() . '.' . $extension;
                    $fileName = $data['DCL_Path']['name'];
                    // Check if everything is OK!
                    //echo $fileName;
                    if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
                        move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
                    } else {
                        echo 'Something went wrong!';
                    }

接口中是否有带有filterstuff的move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName); obsolet?在这种情况下,语法又如何呢?

这是我最大的愿望之一,是否有人知道一种教程,它明确地解释了两种选择(验证器和过滤器)的不同可能性和关键点?有时我无法相信你需要这么多时间来找到合适的钥匙。

编辑1:显示表单,过滤器和更改控制器

这是我的Form类的一部分:

<?php
namespace Import\Form;

use Zend\Form\Form;
class ImportForm extends Form
{
    public function __construct($name = null)
    {
        // We will ignore the name provided to the constructor
        parent::__construct('import');

        $this->add([
                'name' => 'DCLID',
                'type' => 'hidden',
        ]);
        $this->add([
                'name' => 'UnitID',
                'type' => 'text',
                'options' => [
                        'label' => 'equipment',

                ],
        ]);
        $this->add([
                'name' => 'DCL_Path',
                'type' => 'File',
                //'required' => true,
                'options' => [
                        'label' => 'path to file',

                ],
                //              'name' => 'FileRenameUpload',
//              'filters' => [
//                      'target'=>'./public/files',
//                      'useUploadName'=>true,
//                      'useUploadExtension'=>true,
//                      'overwrite'=>true,
//                      'randomize'=>false
//                  ],
//              'validators' => [      // Validators.
//                      // Put validator info here.
//              ]
        ]);

这里扩展了InputFilterAwareInterface

类的一部分
<?php
namespace Import\Model;
use DomainException;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\ToInt;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\StringLength;

class Import implements InputFilterAwareInterface
{
    public $DCLID;
    public $DCL_Path;
    public $Unitname;
    public $UnitID;
    public $Importdate;
    public $Importuser;
    public $Importok;
    public $DCL_Type;
    public $Changed_per_User;
    public $Description_Changes;

    private $inputFilter;

    public function exchangeArray(array $data)
    {
        $this->DCLID= !empty($data['DCLID']) ? $data['DCLID'] : null;
        $this->UnitID= !empty($data['UnitID']) ? $data['UnitID'] : null;
        $this->DCL_Path= !empty($data['DCL_Path']) ? $data['DCL_Path'] : null;
        $this->Importdate= !empty($data['Importdate']) ? $data['Importdate'] : null;
        $this->Importuser= !empty($data['Importuser']) ? $data['Importuser'] : null;
        $this->Importok= !empty($data['Importok']) ? $data['Importok'] : null;
        $this->DCL_Type= !empty($data['DCL_Type']) ? $data['DCL_Type'] : null;
        $this->Changed_per_User= !empty($data['Changed_per_User']) ? $data['Changed_per_User'] : null;
        $this->Description_Changes= !empty($data['Description_Changes']) ? $data['Description_Changes'] : null;
    }

    public function getArrayCopy()
    {
        //      echo var_dump(get_object_vars($this)
        //              );

        return get_object_vars($this);
    }

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new DomainException(sprintf(
                '%s does not allow injection of an alternate input filter',
                __CLASS__
                ));
    }

    public function getInputFilter()
    {
        if ($this->inputFilter) {
            return $this->inputFilter;
        }

        $inputFilter = new InputFilter();

//      $inputFilter->add([
//              'name' => 'DCLID',
//              'required' => false,
//              'filters' => [
//                      ['name' => ToInt::class],
//              ],
//      ]);
        // Validator für das Upload Element

        $inputFilter->add([
                'type'     => 'Zend\InputFilter\FileInput',
                'name'     => 'DCL_Path',  // Element's name.
                'required' => true,    // Whether the field is required.
                'filters'  => [        // Filters.
                        [
                                'name' => \Zend\Filter\File\RenameUpload::class,
                                'options' => [
                                        'use_upload_extension' => true,
                                        'randomize' => false,
                                        'overwrite' => true,
                                        'target' => 'public/files',
                                ],
                        ],
                ],
                'validators' => [      // Validators.
                        [
                                'name' => \Zend\Validator\File\Extension::class,
                                'options' => [
                                        'extension' => 'xls, xlsx',
                                        'message' => 'File extension not match',
                                ],
                        ],
                        [
                                'name' => \Zend\Validator\File\MimeType::class,
                                'options' => [
                                        'mimeType' => 'text/xls', 'text/xlsx',
                                        'message' => 'File type not match',
                                ],
                        ],
                        [
                                'name' => \Zend\Validator\File\Size::class,
                                'options' => [
                                        'min' => '1kB',  // minimum of 1kB
                                        'max' => '4MB',
                                        'message' => 'File too large',
                                ],
                        ],
                ]
        ]);

和我的控制部分,我认为可能存在问题,可能不是逻辑:

$form = new ImportForm();
        $form->get('submit')->setValue('Add');  //Änderung des LAbels des Submit Buttons, um das Form wiederverwenden zu können
        //echo "hier";
        $request = $this->getRequest();
        if (! $request->isPost()) {     //wurden  Daten über POST geschickt?
            return ['form' => $form];   //Keine Daten, nur Form anzeigen, nicht verarbeiten
        }   
        else {
        //Es wurden Daten gesendet
            //echo "Daten";
            $import = new Import();     //Neue Instanz von Import
            $form->setInputFilter($import->getInputFilter());       //Filter an Form binden
            $form->setData($request->getPost());        //Daten abholen
            //echo $form->isValid();
            if (! $form->isValid()) {
                return ['form' => $form];       //Wenn die Daten nicht valide sind
            }   
            else{           //aus Tableadapter
                    $import->exchangeArray($form->getData());
                    $data = array_merge_recursive(
                            $this->getRequest()->getPost()->toArray(),
                            $this->getRequest()->getFiles()->toArray()
                            );
                    $form->setData($data);
                    if ($form->isValid()) {
                        $data = $form->getData();
                        // Upload path
                //      $location = "public/files/";
//                      $allowedExtension = array('xls', 'xlsx');
//                      $extension = explode('.', $data['DCL_Path']['name']);
//                      $extension = end($extension);
                        $fileName = $data['DCL_Path']['name'];
//                      // Check if everything is OK!
//                      //echo $fileName;
//                      if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
//                          move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
//                      } else {
//                          echo 'Something went wrong!';
//                      }

                        //-----------------------------------------------------------------
                        // t_dcl befüllen
                        //-----------------------------------------------------------------
                        //$namen = explode(",", $import ); //Konvertierung des Strings in ein Array
                        //echo "<pre>"; var_dump($namen); echo "</pre>"; //Formartierte Ausgabe des Arrays
                        $this->table->saveImport($import);  

EDIT2:发布部分控制权以讨论某些陈述的顺序:

controlleraction

$form = new ImportForm();
        $form->get('submit')->setValue('Add');  
        $request = $this->getRequest();
        if (! $request->isPost()) {     
            return ['form' => $form];   
        }   
        else {
            $import = new Import();     //Neue Instanz von Import
            $form->setInputFilter($import->getInputFilter());       
            $form->setData($request->getPost());        
            $data = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray(),
                    $this->getRequest()->getFiles()->toArray()
                    );
            $form->setData($data);
            if (! $form->isValid()) {
                return ['form' => $form];       
            }   
            else{           
                    $import->exchangeArray($form->getData());
                    $data = $form->getData();
                    $fileName = $data['DCL_Path']['name'];

$form->setInputFilter($import->getInputFilter());的位置是否正确?或者什么时候必须将Inputfilter绑定到表单?

还有一个小问题:我现在有一条消息:

  

文件类型不匹配

我尝试上传.xlsx文件

1 个答案:

答案 0 :(得分:1)

请为InputFilter

试试
        $inputFilter->add([
            'type'     => 'Zend\InputFilter\FileInput',
            'name'     => 'DCL_Path',  // Element's name.
            'required' => true,    // Whether the field is required.
            'filters'  => [        // Filters.
                [
                    'name' => \Zend\Filter\File\RenameUpload::class,
                    'options' => [
                        'use_upload_extension' => true,
                        'randomize' => false,
                        'overwrite' => true,
                        'target' => 'public/files',
                    ],
                ],
            ],
            'validators' => [      // Validators.
                [
                    'name' => \Zend\Validator\File\Extension::class,
                    'options' => [
                        'extension' => 'xls, xlsx',
                        'message' => 'File extension not match',
                    ],
                ],
                [
                    'name' => \Zend\Validator\File\MimeType::class,
                    'options' => [
                        'mimeType' => 'text/xls', 'text/xlsx',
                        'message' => 'File type not match',
                    ],
                ],
                [
                    'name' => \Zend\Validator\File\Size::class,
                    'options' => [
                        'max' => '4MB',
                        'message' => 'File too large',
                    ],
                ],
            ]
        ]);

这里是控制器

    if($this->getRequest()->isPost()) {
        // merge post and files
        $request = $this->getRequest();
        $data = array_merge_recursive(
            $request->getPost()->toArray(),
            $request->getFiles()->toArray()
        );

        // passing data
        $form->setData($data);

        // execute validator
        if($form->isValid()) {
            // execute file filters.
            $data = $form->getData();
        }
    }

使用\Zend\Validator\File\Extension\Zend\Validator\File\MimeType\Zend\Validator\File\FileSize您无需使用此代码在您的控制器中手动检查。

if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {}

因为我们在致电$form->isValid()时会执行验证。

使用\Zend\Filter\File\RenameUpload,您不再需要move_uploaded_file()了。因为此过滤器会将上传的文件移动到我们在'target' => 'public/files'选项中定义的目标文件。

当我们致电$form->getData();

时执行过滤

关于ValidatorFilter的解释,我建议您创建另一篇文章。通过使用单独的问题,可以很容易地在搜索引擎中搜索并帮助其他人找到它。