我想做上传文件的简单操作(多个)。我从客户端获得的附件如:
var data = new FormData();
_.some(this.collection.models, function(model, index) {
data.append('file_'+index, model.get('_FILE'));
}
在服务器端,我尝试通过Http适配器执行验证过程。假设附加了一个文件:
$_files = $this->params()->fromFiles();
print_r($_files[0]);
$extension = new \Zend\Validator\File\Extension('jpeg,jpg');
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->addValidator($extension);
if($extension->isValid($_files[0]))
{
echo 'valid';
} else {
$messages = $extension->getMessages();
echo implode("\n", $messages);
}
if($adapter->isValid($_files[0]))
{
echo 'valid';
} else {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
...和方法$ adapter-> isValid()无效。但$ extension-> isValid()工作正常。
Array (
[name] => untitled_test.png
[type] => image/png
[tmp_name] => /tmp/phpRPlV8G
[error] => 0 [size] => 398
)
答案 0 :(得分:0)
对于文件上传,有一个特殊的Zend\Validator\File\UploadFile
验证器。我认为你应该考虑使用这个课程。您可以在 here in the documentation 找到更多相关信息。
它会自动用在FileInput
类中,这是$_FILES
数组中上传文件的特殊输入类型。
详细了解如何使用/实施此 in the official ZF2 documentation here 。
答案 1 :(得分:0)
当我创建\ Zend \ File \ Transfer \ Adapter \ Http()的实例时,类构造函数默认加载所有发布的文件($ _FILES)。 这是我的完整解决方案。也许有人会有用。
/**
* Upload multiple images
*
* @return JsonModel
*/
public function imageAction()
{
$request = $this->getRequest();
$uploadStatus = [];
if ($request->isXmlHttpRequest())
{
$models = $this->params()->fromPost('models');
$adapter = new \Zend\File\Transfer\Adapter\Http();
$size = new \Zend\Validator\File\Size(['min' => '100B', 'max' => '10MB','useByteString' => true]);
$extension = new \Zend\Validator\File\Extension(['jpg','gif','png','jpeg'], true);
if (extension_loaded('fileinfo'))
{
$adapter->setValidators([new \Zend\Validator\File\IsImage()]);
}
$adapter->setValidators([$size, $extension]);
foreach($models as $index => $rawModel)
{
/**
* Parse JSON model
*/
$model = json_decode($rawModel,true);
/**
* Get full filename
*/
$_file = $adapter->getFileInfo('file_'.$model['index'])['file_'.$model['index']]['name'];
if (!$adapter->isValid($_file))
{
foreach ($adapter->getMessages() as $key => $msg)
{
$uploadStatus['errorFiles'][] = $_file.' '.strtolower($msg);
}
}
$filename = $this->appPlugin()->generateFilename($model['name']);
$filepath = $this->appPlugin()->getImageDestination();
$adapter->addFilter('File\Rename', ['target' => $filepath.$filename, 'overwrite' => true]);
if (!$adapter->receive($_file))
{
$uploadStatus["errorFiles"][] = $_file.' was not uploaded';
} else {
$uploadStatus["successFiles"][] = $_file.' was successfully uploaded';
}
}
}
return new JsonModel(['uploadStatus'=>$uploadStatus]);
}
完整示例在这里http://learnzf2.sitrun-tech.com/learn-zf2-ajax-image-gallery。谢谢社区。 p>