我尝试使用ZF2上传文件,但文件未上传。表格似乎是有效的。我的代码有什么问题吗?
如果我使用php move_uploaded_files
上传图片,一切都按预期工作。
形式:
class LogoUploadForm extends Form {
public function init() {
$this->add([
'type' => 'File',
'name' => 'logo',
'attributes' => array(
'id' => 'logo-input'
),
]);
}
}
InputFilter输入:
class LogoInputFilter extends InputFilter {
public function init() {
$this->add([
'name' => 'logo',
'required' => true,
'filters' => [
[
'name' => 'File\RenameUpload',
'options' => [
'target' => './data/upload/',
'overwrite' => true,
'randomize' => true,
'use_upload_extension' => true,
]
]
],
'validators' => [
[
'name' => 'File\MimeType',
'options' => [
'magicFile' => false, //Important: https://github.com/zendframework/zf2/issues/6493
'mimeType' => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
]
],
[
'name' => 'File\UploadFile',
],
[
'name' => 'File\Size',
'options' => [
'max' => '4MB'
]
]
]
]);
}
}
控制器:
class LogoController extends AbstractActionController {
public function uploadAction() {
$form = $this->logoUploadForm;
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData(array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
));
if ($form->isValid()) {
exit('valid');
} else {
exit('invalid');
}
}
}
}
答案 0 :(得分:0)
您应该在窗体opentag函数前调用prepare函数:
$form->prepare();
echo $this->form()->openTag($form);
在您调用prepare函数时,表单将检测要使用的正确表单编码类型。