我正在尝试创建一个为我上传文件的控制器,但我总是得到相同的结果。该文件无效,因此他无法上传。
我的控制器中的功能是:
$upload = new \Zend\File\Transfer\Transfer();
$upload->setDestination('./data/images/uploads/');
$rtn = array('success' => null);
if ($this->getRequest()->isPost()) {
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if (!$upload->isUploaded($file)) {
print "<h3>Not Uploaded</h3>";
\Zend\Debug\Debug::dump($file);
continue;
}
if (!$upload->isValid($file)) {
print "<h4>Not Valid</h4>";
\Zend\Debug\Debug::dump($file);
continue;
}
}
$rtn['success'] = $upload->receive();
}
return new \Zend\View\Model\JsonModel($rtn);
结果是:
<h4>Not Valid</h4><pre>string(8) "files_0_"
</pre>{"success":false}
当我查看$ files(print_r())时,我得到:
Array
(
[files_0_] => Array
(
[name] => logo_welcome.gif
[type] => image/gif
[tmp_name] => /private/var/tmp/phpiufvIc
[error] => 0
[size] => 62935
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[validated] =>
[received] =>
[filtered] =>
[validators] => Array
(
[0] => Zend\Validator\File\Upload
)
[destination] => ./data/images/uploads
)
)
答案 0 :(得分:0)
正如您在ZF2 docs中所看到的,不推荐使用Zend\File\Transfer
上传文件,而是赞成使用标准的ZF2 Zend\Form
和Zend\InputFilter
功能。
话虽如此,您应该使用Zend\Filter\File\RenameUpload
来移动上传的文件。您只需将Zend\Filter\File\RenameUpload
过滤器附加到InputFilter
规范中,就像那样:
$this->add([
'name' => 'file',
'type' => 'Zend\InputFilter\FileInput',
'filters' => [
[
'name' => 'FileRenameUpload',
'options' => [
'target' => realpath('./data/uploads/'),
'randomize' => true,
'use_upload_extension' => true,
],
],
],
]);
在你的控制器动作中:
if ($this->request->isPost()) {
$post = array_merge_recursive(
$this->request->getPost()->toArray(),
$this->request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
// File uploaded and moved to data/uploads folder
}
}
查看official documentation中的完整示例。