Skip to content

Instantly share code, notes, and snippets.

@hmbilal
Last active May 23, 2018 10:17
Show Gist options
  • Save hmbilal/b17e88af5e4f366e5256 to your computer and use it in GitHub Desktop.
Save hmbilal/b17e88af5e4f366e5256 to your computer and use it in GitHub Desktop.
Uploading multiple files in Zend Framework 2 (solution for file is uploaded illegally in zf2)
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Lists\Entity\Lists;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$listEntity = new Lists();
$builder = new AnnotationBuilder();
$form = $builder->createForm($listEntity);
$form->setAttribute('enctype', 'multipart/form-data');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setValidationGroup('house_decision', 'house_wishlist', 'permit', 'inspection');
$form->setData($request->getPost());
if ($form->isValid()) {
$files = $this->upload();
if ($files['status'] == 'success') {
// save everything
} else {
foreach ($files['messages'] as $key => $file) {
if ($file['status'] == 'error') {
$form->get($key)->setMessages($file['errors']);
}
}
} // $files['status'] == 'success'
} // isValid()
} // isPost()
return new ViewModel(array(
'form' => $form,
));
}
public function upload($allowed = array('pdf'))
{
$messages = array('status' => 'success');
$files = $this->params()->fromFiles();
foreach ($files as $key => $file) {
if (!empty($file['name'])) {
$adapter = new \Zend\File\Transfer\Adapter\Http();
$size = new \Zend\Validator\File\Size(array('min' => 1, 'max' => 31457280)); // minimum bytes filesize, max too..
$extension = new \Zend\Validator\File\Extension(array('extension' => $allowed));
// rename file
$rename = new \Zend\Filter\File\Rename(array(
'target' => str_replace(array(' ', '$'), '-', $file['name']),
'randomize' => true,
'overwrite' => true,
));
$adapter->setValidators(array($size, $extension), $file['name']);
$adapter->setFilters(array($rename), $file['name']);
/**
* Valid Upload
*/
if ($adapter->isValid($key)) { // $key is field name in the form
$adapter->setDestination('public/' . FILES_PATH);
if ($adapter->receive($key)) { // $key is field name in the form
$uploadedFile = $adapter->getFileInfo();
$messages['status'] = 'success';
$messages['messages'][$key] = array(
'filename' => $uploadedFile[$key]['name'],
'status' => 'success',
'message' => 'File uploaded successfully!',
);
}
} else {
$messages['status'] = 'error';
$messages['messages'][$key] = array(
'status' => 'error',
'errors' => $adapter->getMessages(),
);
break;
}
} // !empty($file)
}
return $messages;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment