简体   繁体   中英

ZF2 File upload validator always false

In my form I have a file upload validator as the code below. The problem I am facing is that the adapter always send me a false on the validation. My question is what am I missing?

Below, code example and output;

# Set form data
$form->setValidationGroup('firstname', 'lastname');
$form->setData($request->getPost());

# Get file uploads
$file = $this->params()->fromFiles('avatar');

# Set image validators
$size      = new Size(array('min' => 0, 'max' => 1024000)); // 5kb / 500kb
$extension = new Extension(array('jpg', 'jpeg', 'gif', 'png'));
$adapter   = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size, $extension), $file['name']);

Debug::dump($file);
Debug::dump($adapter->isValid());
Debug::dump($adapter->getMessages());
exit();


Output;

array(5) {
  ["name"] => string(10) "avatar.png"
  ["type"] => string(9) "image/png"
  ["tmp_name"] => string(14) "/tmp/phptkaBvc"
  ["error"] => int(0)
  ["size"] => int(171961)
}

bool(false)

array(1) {
  ["fileUploadErrorNoFile"] => string(24) "File '' was not uploaded"
}

Regards, Nik

$adapter->setDestination('/tmp');

Did the trick. :)

With ZF2 forms the correct method to upload files is to use the File element on the form and a matching FileInput on the InputFilter. The linked documentation pages show how to configure each.

Take note that you have to merge the POST and FILES data together and send that to $form->setData , as the InputFilter example shows. I failed to notice that the first time I built an upload form and it took embarrassingly much debugging to find the cause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM