gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:10:24 27 4
gpt4 key购买 nike

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

我知道你们中的许多人会认为这个问题太模糊了,但是创建需要更多处理的表单元素的最佳方法是什么?

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

我被引导转向传输适配器,但代码看起来不太像 ZF2。

很抱歉,这是一个如此模糊的问题,我希望它能引起同情。很难学习一个文档很少的框架,再加上我的 zend framework 1 知识有点薄,进展有点慢。

一旦我有了一个很好的例子,我也许会找个地方发布它。

最佳答案

很简单:
[在你的 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();
}
}
}

更新:我找到了将文件验证与表单验证结合使用的更好方法:
将此类添加到您的模块中,例如: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;
}
}

}

在表单中使用并添加 filterInput :

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

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

关于php - 如何在 Zend Framework 2 中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11718809/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com