Actually I'm developing a simple file uploader.
In the ImageUploader.php file I define the getInputFilter function, all works unless I try to add a File\MimeType validator:
<?php
namespace Admin\Model;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\File\MimeType; //tried also with use Zend\Validator\File;
[...]
public function getInputFilter()
{
[...]
$inputFilter->add($factory->createInput(array(
'name' => 'image',
'required' => true,
'validators' => array(
array(
'name' => 'MimeType', //tried also with File\MimeType
'options' => array(
'mimeType' => array('image/jpeg'),
),
),
),
)));
[...]
}
What's the correct way to define a File\Validator\MimeType?
Thank you in advance.
Here is a sample from my project with a couple of other useful features (renaming for example):
use Zend\File\Transfer\Adapter\Http,
Zend\Validator\File\Size,
Zend\Validator\File\IsImage;
[...]
public function editAction() {
[...]
if ($request->isPost()) {
$params = $this->params()->fromPost();
$files = $this->params()->fromFiles();
$images = array();
if(!empty($files['main_image']['name'])) $images['main_image'] = $files['main_image']['name'];
if(!empty($files['detailed_image']['name'])) $images['detailed_image'] = $files['detailed_image']['name'];
if(!empty($images)) {
$adapter = new Http();
$size = new Size(array('max'=>1000000));
$is_image = new IsImage();
$image_errors = array();
foreach ($images as $field => $filename) {
$adapter->setValidators(array($size,$is_image), $filename);
if (!$adapter->isValid($filename)) {
$adapter_errors = $adapter->getMessages();
$errors = array();
foreach($adapter_errors as $key=>$row) {
$errors[] = $row;
}
if(!empty($errors)) {
array_push($image_errors, $errors);
$form->setMessages(array($field => $errors));
}
} else {
$adapter->setDestination(IMAGES_PATH);
$fileinfo = $adapter->getFileInfo();
preg_match('/.+\/(.+)/', $fileinfo[$field]['type'], $matches);
$extension = $matches[1];
$old_filename = $item->__get($field);
$new_filename = $item->id.'_'.$field.'.'.$extension;
$adapter->addFilter('File\Rename',
array(
'target' => IMAGES_PATH.$new_filename,
'overwrite' => true,
)
);
if($adapter->receive($fileinfo[$field]['name'])) {
if(!empty($old_filename) && $old_filename != $new_filename &&
file_exists(IMAGES_PATH.$old_filename)) {
unlink(IMAGES_PATH.$old_filename);
}
$params[$field] = $new_filename;
}
}
}
}
}
[...]
}
[...]
The code however could be refactored to move the logic to some lib or model.