php 如何在 Zend Framework 2 中上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11718809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:56:24  来源:igfitidea点击:

How do I do File uploading in Zend Framework 2?

phpformszend-framework2

提问by thomas-peter

I have been looking into file uploading in ZF2.

我一直在研究 ZF2 中的文件上传。

I understand that many of you will think that this is too vague a question, but what is the best way to create form elements which have a bit more processing?

我知道你们中的许多人会认为这是一个过于模糊的问题,但是创建具有更多处理功能的表单元素的最佳方法是什么?

I can't seem to work out where to start. I have ruled out processing it in the controller as this will break DRY principles. The form object doesn't seem to have a place to 'hook' any code into. The view helper is just that, for the view so it doesn't make sense to do anything in that. So that leaves the input filter. That doesn't seem right either.

我似乎不知道从哪里开始。我已经排除了在控制器中处理它的可能性,因为这会破坏 DRY 原则。表单对象似乎没有可以“挂钩”任何代码的地方。视图助手就是这样,对于视图,因此在其中做任何事情都没有意义。这样就留下了输入过滤器。这似乎也不对。

I have been steered towards transfer adapters but the code looks like it's not very ZF2.

我一直在使用传输适配器,但代码看起来不是很 ZF2。

I'm sorry that this is such a vague question and I'm hoping it falls on sympathetic ears. It's hard learning a framework that has very little documentation and compounded with the fact that my zend framework 1 knowledge is a little thin it, progress is a little slow.

很抱歉,这是一个如此含糊的问题,我希望它落在有同情心的人的耳朵里。学习一个文档很少的框架很难,而且我的 Zend 框架 1 知识有点薄弱,进展有点慢。

Once I have a good example working I will perhaps find some place to post it.

一旦我有一个很好的例子工作,我可能会找到一些地方来张贴它。

回答by M Rostami

it's simple:
[In Your Controller]

很简单:
[在你的控制器中]

$request = $this->getRequest();
if($request->isPost()) { 
     $files =  $request->getFiles()->toArray();
     $httpadapter = new \Zend\File\Transfer\Adapter\Http(); 
     $filesize  = new \Zend\Validator\File\Size(array('min' => 1000 )); //1KB  
     $extension = new \Zend\Validator\File\Extension(array('extension' => array('txt')));
     $httpadapter->setValidators(array($filesize, $extension), $files['file']['name']);
     if($httpadapter->isValid()) {
         $httpadapter->setDestination('uploads/');
         if($httpadapter->receive($files['file']['name'])) {
             $newfile = $httpadapter->getFileName(); 
         }
     }
} 

UPDATE: I found better way to use file validation with form validation :
Add this class to your module e.g : Application/Validators/File/Image.php

更新:我找到了将文件验证与表单验证一起使用的更好方法:
将此类添加到您的模块中,例如:Application/Validators/File/Image.php

<?php
namespace Application\Validators\File;

use Application\Validator\FileValidatorInterface;
use Zend\Validator\File\Extension;
use Zend\File\Transfer\Adapter\Http;
use Zend\Validator\File\FilesSize;
use Zend\Filter\File\Rename;
use Zend\Validator\File\MimeType;
use Zend\Validator\AbstractValidator;

class Image extends AbstractValidator
{  
    const FILE_EXTENSION_ERROR  = 'invalidFileExtention';
    const FILE_NAME_ERROR       = 'invalidFileName'; 
    const FILE_INVALID          = 'invalidFile'; 
    const FALSE_EXTENSION       = 'fileExtensionFalse';
    const NOT_FOUND             = 'fileExtensionNotFound';
    const TOO_BIG               = 'fileFilesSizeTooBig';
    const TOO_SMALL             = 'fileFilesSizeTooSmall';
    const NOT_READABLE          = 'fileFilesSizeNotReadable';


    public $minSize = 64;  //KB
    public $maxSize = 1024; //KB
    public $overwrite = true;
    public $newFileName = null;
    public $uploadPath = './data/';
    public $extensions = array('jpg', 'png', 'gif', 'jpeg');
    public $mimeTypes = array(
                    'image/gif',
                    'image/jpg',
                    'image/png',
            );

    protected $messageTemplates = array(   
            self::FILE_EXTENSION_ERROR  => "File extension is not correct", 
            self::FILE_NAME_ERROR       => "File name is not correct",  
            self::FILE_INVALID          => "File is not valid", 
            self::FALSE_EXTENSION       => "File has an incorrect extension",
            self::NOT_FOUND             => "File is not readable or does not exist", 
            self::TOO_BIG               => "All files in sum should have a maximum size of '%max%' but '%size%' were detected",
            self::TOO_SMALL             => "All files in sum should have a minimum size of '%min%' but '%size%' were detected",
            self::NOT_READABLE          => "One or more files can not be read", 
    );

    protected $fileAdapter;

    protected $validators;

    protected $filters;

    public function __construct($options)
    {
        $this->fileAdapter = new Http();  
        parent::__construct($options);
    }

    public function isValid($fileInput)
    {   
        $options = $this->getOptions(); 
        $extensions = $this->extensions;
        $minSize    = $this->minSize; 
        $maxSize    = $this->maxSize; 
        $newFileName = $this->newFileName;
        $uploadPath = $this->uploadPath;
        $overwrite = $this->overwrite;
        if (array_key_exists('extensions', $options)) {
            $extensions = $options['extensions'];
        } 
        if (array_key_exists('minSize', $options)) {
            $minSize = $options['minSize'];
        }  
        if (array_key_exists('maxSize', $options)) {
            $maxSize = $options['maxSize'];
        } 
        if (array_key_exists('newFileName', $options)) {
            $newFileName = $options['newFileName'];
        } 
        if (array_key_exists('uploadPath', $options)) {
            $uploadPath = $options['uploadPath'];
        } 
        if (array_key_exists('overwrite', $options)) {
            $overwrite = $options['overwrite'];
        }    
        $fileName   = $fileInput['name']; 
        $fileSizeOptions = null;
        if ($minSize) {
            $fileSizeOptions['min'] = $minSize*1024 ;
        }
        if ($maxSize) {
            $fileSizeOptions['max'] = $maxSize*1024 ;
        }
        if ($fileSizeOptions) {
            $this->validators[] = new FilesSize($fileSizeOptions); 
        }
        $this->validators[] = new Extension(array('extension' => $extensions));
        if (! preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $fileName)) {
            $this->error(self::FILE_NAME_ERROR);
            return false; 
        }

        $extension = pathinfo($fileName, PATHINFO_EXTENSION); 
        if (! in_array($extension, $extensions)) {
            $this->error(self::FILE_EXTENSION_ERROR);
            return false; 
        }
        if ($newFileName) {
            $destination = $newFileName.".$extension";
            if (! preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $destination)) {
                $this->error(self::FILE_NAME_ERROR);
                return false;  
            }
        } else {
            $destination = $fileName;
        } 
        $renameOptions['target'] = $uploadPath.$destination;
        $renameOptions['overwrite'] = $overwrite;
        $this->filters[] = new Rename($renameOptions); 
        $this->fileAdapter->setFilters($this->filters);
        $this->fileAdapter->setValidators($this->validators); 
        if ($this->fileAdapter->isValid()) { 
            $this->fileAdapter->receive();
            return true;
        } else {   
            $messages = $this->fileAdapter->getMessages(); 
            if ($messages) {
                $this->setMessages($messages);
                foreach ($messages as $key => $value) { 
                    $this->error($key);
                }
            } else {
                $this->error(self::FILE_INVALID);
            }
            return false;
        }
    } 

}

Use in form and add filterInput :

在表单中使用并添加 filterInput :

    array(
        'name' => 'file',
        'required' => true,
        'validators' => array(
            array(
                'name' => '\Application\Validators\File\Image',
                'options' => array(
                        'minSize' => '64',
                        'maxSize' => '1024',
                        'newFileName' => 'newFileName2',
                        'uploadPath' => './data/'
                )
            )
        )
    )

And in your controller :

在您的控制器中:

    $postData = array_merge_recursive((array)$request->getPost(), (array)$request->getFiles());
    $sampleForm->setData($postData);  
    if ($sampleForm->isValid()) { 
        //File will be upload, when isValid returns true;
    } else {
        var_dump($sampleForm->getMessages());
    }

回答by Vinicius Garcia

This is a old question, but in case someone else get here, I found this good article:

这是一个老问题,但万一其他人来到这里,我发现了这篇好文章:

Create Simple Upload Form with File Validation

使用文件验证创建简单的上传表单

This is a good start to work with files in ZF2. ;)

这是在 ZF2 中处理文件的良好开端。;)

回答by Antoine Hedgecock

From what i asked / seen in irc (#Zftalk.2) the file component is yet to be refactored

从我在 irc (#Zftalk.2) 中询问/看到的文件组件尚未重构

回答by Victor Odiah

to retrieve the $_FILES, you do the following in the controller:

要检索 $_FILES,请在控制器中执行以下操作:

$request= $this->getRequest();

    if($request->isPost()){
        $post= array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
        print_r($post);
    }

This post is old but i hope this helps someone.

这篇文章很旧,但我希望这对某人有所帮助。

回答by michaelbn

File upload factory and validation is scheduled to ZF2.1

文件上传工厂和验证计划到ZF2.1

Mean while I use $_FILES :(

意思是我使用 $_FILES :(

Check the following links:

检查以下链接: