检查下面的代码,我从上传中获取文件,我想验证它。我检查文件扩展名、大小和 MIME。如果我一一检查结果是正确的,但是当我使用 $adapter->setValidators() 结果是误报。
ZF2 验证器的行为方式是否怪异,或者我不明白我应该如何使用它?
代码
<?php
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
/* set mime on server side */
$finfo = new \finfo(FILEINFO_MIME);
$mimeinfo = explode(';', $finfo->file($data['upload_image']['tmp_name']));
$data['upload_image']['type'] = $mimeinfo[0];
$adapter = new \Zend\File\Transfer\Adapter\Http();
$validatorSize = new \Zend\Validator\File\Size(10);
$validatorExt = new \Zend\Validator\File\Extension('gif,jpg,jpeg,png');
$validatorMime = new \Zend\Validator\File\MimeType('image/gif,image/jpg,image/jpeg,image/png');
$results = array();
$results['size'] = $validatorSize->isValid($data['upload_image']);
$results['ext'] = $validatorExt->isValid($data['upload_image']);
$results['mime'] = $validatorMime->isValid($data['upload_image']);
$adapter->setValidators(array(
$validatorSize,
$validatorExt,
$validatorMime,
), $data['upload_image']);
$results['adapter'] = $adapter->isValid();
\Zend\Debug\Debug::dump($results);
?>
结果
array(4) {
["size"] => bool(false)
["ext"] => bool(true)
["mime"] => bool(false)
["adapter"] => bool(true)
}