我如何在Zend Framework 2中上传文件? [英] How do I do File uploading in Zend Framework 2?

查看:126
本文介绍了我如何在Zend Framework 2中上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我明白你们中许多人会认为这个问题太模糊了,但创建具有更多处理的表单元素的最佳方式是什么?

p>

我似乎无法确定从哪里开始。我已经排除了在控制器中处理它,因为这会打破DRY原则。表单对象似乎没有一个'钩住'任何代码的地方。视图助手就是这样,对于视图来说,做任何事情都没有意义。这样就离开了输入过滤器。这看起来不正确。



我一直在转向转接适配器,但代码看起来不像ZF2。



对不起,这是一个模糊的问题,我希望它落在同情的耳朵上。这是一个很难学习的框架,只有很少的文档,并且事实证明我的zend框架1的知识有点薄,它的进展有点慢。



一旦我有一个很好的例子,我可能会找到一些地方发布它。

解决方案

很简单:

[在您的控制器中]

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


$ b

更新 strong>:
我发现使用文件验证与表单验证更好的方法:

将此类添加到您的模块中,例如:Application / Validators / File / Image.php

 <?php 
名称空间Application \Validators\File;

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

类图像扩展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 =>文件扩展名不正确,
self :: FILE_NAME_ERROR =>文件名不正确,
self :: FILE_INVALID =>文件无效,
self :: FALSE_EXTENSION =>文件扩展名不正确,
self :: NOT_FOUND => 文件不可读或不存在,
self :: TOO_BIG =>总计所有文件的最大大小应为'%max%',但'%size%'被检测到,
self :: TOO_SMALL =>总计所有文件的最小大小应为'%min%',但检测到'%size%',
self :: NOT_READABLE =>一个或多个文件不能被读取,
);

保护$ fileAdapter;

保护$ validators;

保护$ 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;
$覆盖= $ this->覆盖;
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)){
$这 - >误差(个体:: FILE_NAME_ERROR);
返回false;
}

$ extension = pathinfo($ fileName,PATHINFO_EXTENSION);
if(!in_array($ extension,$ extensions)){
$ this-> error(self :: FILE_EXTENSION_ERROR);
返回false;
}
if($ newFileName){
$ destination = $ newFileName。。$ extension;
if(!preg_match('/ ^ [a-z0-9 -_] + [a-z0-9-_\。] + $ / i',$ destination)){
$这 - >误差(个体:: FILE_NAME_ERROR);
返回false;
}
} else {
$ destination = $ fileName;
}
$ renameOptions ['target'] = $ uploadPath。$ destination;
$ renameOptions ['overwrite'] = $覆盖;
$ this-> filters [] = new Rename($ renameOptions);
$ this-> fileAdapter-> setFilters($ this-> filters);
$ this-> fileAdapter-> setValidators($ this-> validators);
if($ this-> fileAdapter-> isValid()){
$ this-> fileAdapter-> receive();
返回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);
}
返回false;



$ b $ / code>

表格并添加filterInput:

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






在您的控制器中: = array_merge_recursive((array)$ request-> getPost(),(array)$ request-> getFiles());
$ sampleForm-> setData($ postData);
if($ sampleForm-> isValid()){
//当isValid返回true时,文件将被上传;
} else {
var_dump($ sampleForm-> getMessages());
}


I have been looking into file uploading in 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.

I have been steered towards transfer adapters but the code looks like it's not very 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.

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

解决方案

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

<?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 :

    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());
    }

这篇关于我如何在Zend Framework 2中上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆