Do we have input filters that allows the user to upload file of specific types (pdf, doc, ,.odt etc) and do not permit to upload files of type - .png, jpg etc.
Please have a look at the validators for files in the documentation:
In the following snippet the execution never goes into the MyValidator:
private function addInputFilter()
{
$inputFilter = new InputFilter();
// File Input
$fileInput = new FileInput('fieldOne');
$isRequired = false;
if($this->scenario == 'create')
$isRequired = true;
$fileInput->setRequired($isRequired);
$fileInput->getFilterChain()->attachByName(
'filerenameupload',
[
'target' => './data/documents/formtemplate',
'use_upload_extension' => true,
]
);
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
// Only allow 'pdf
$fileValidator = new MimeType('application/pdf');
// Perform validation
if ($fileValidator->isValid('./myfile.pdf')) {
// file is valid
}
$inputFilter->add([
'name' => 'fieldOne',
'required' => true,
'validators' => [
[
'name' => MyValidator::class,
'options' => [
'item' => $this->fieldOne,
'scenario' => $this->scenario,
'itemType' => 'fieldOne',
'max' => 128,
],
],
],
]);
}
My objective is to have the file-type validation logic in MyValidator, that is the following code segment need to be in MyValidator:
$fileValidator = new MimeType('application/pdf');
// Perform validation
if ($fileValidator->isValid('./myfile.pdf')) {
// file is valid
}
But I am stuck in the basic thing - execution don’t go in there at all.
Add the Mime validator to your input filter:
$inputFilter = new Laminas\InputFilter\InputFilter();
$inputFilter->add(
[
'type' => Laminas\InputFilter\FileInput::class,
'name' => 'fieldOne',
'required' => $this->scenario === 'create',
'filters' => [
[
'name' => Laminas\Filter\File\RenameUpload::class,
'options' => [
'target' => './data/documents/formtemplate',
'use_upload_extension' => true,
],
],
// add here other filters…
],
'validators' => [
[
'name' => Laminas\Validator\File\MimeType::class,
'options' => [
'mimeType' => 'application/pdf',
],
],
// add here other validators…
],
]
);