I'm trying to upload an image, very basic. Here's my input filter file:
namespace MyNamespace;
use Zend\InputFilter\InputFilter;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\File\RenameUpload;
use Zend\Validator\File\Size;
use Zend\Validator\File\MimeType;
class MyFilter extends InputFilter
{
public function __construct()
{
$this->add(
[
'name' => 'image',
'required' => true,
'filters' => [
[
/* 'name' => RenameUpload::class, */
'name' => 'filerenameupload',
'options' => [
'target' => './data/uploads/images/.ext',
'overwrite' => true,
'randomize' => true,
'use_upload_extension' => true,
]
]
],
'validators' => [
[
'name' => Size::class,
'options' => [
'max' => '10MB',
],
],
[
'name' => MimeType::class,
'options' => [
'mimeType' => [
'image/jpg',
'image/jpeg',
'image/png'
]
],
],
],
]
);
}
...
I checked $request->getFiles()->toArray()
and the uploaded image is there. In the controller I do:
$postData = array_merge (
$this->request->getPost()->toArray(),
$this->request->getFiles()->toArray()
);
$form = new MyForm;
$form->setInputFilter(new MyFilter);
$form->setData($postData);
$form->isValid() // this returns true.
When I check the uploads folder, nothing is there. It's not a filesystem issue since the folder owner is the same as the user running apache; and the permissions are 755.
I also noticed if I delete the folder where it's suppose to write to, $form->isValid()
still returns true
.
What am I doing wrong?
Provide the proper upload directory if you want to use the RenameUpload filter. Like the following
'./data/upload/images/'
Use array_merge_recursive() instead of array_merge(). Because array_merge() orverrides similar array keys (just keeps the last one).
And this will upload the the image to the target assigned by the RenameUpload filter.
<?php
...
if($form->isValid()) {
// Move uploaded file to the assigned directory.
$data = $form->getData();
// Do other stuff
...
}