Zend Framework 2 : Create Simple Upload Form with File Validation
Zend Framework 2 has Zend\File\Transfer component that can provide file transfer need for our application. We can add Files validator and pass error message to Zend\Form component object, that can be retrieve by view if process was failed. We can add another validator instead of Upload validator that registered by default in Http Adapter.
For example, i have upload form like this :
The code form will be like the following :
// filename : module/Test/src/Test/Form/ProfileForm.php namespace Test\Form; use Zend\Form\Form; class ProfileForm extends Form { public function __construct($name = null) { parent::__construct('Profile'); $this->setAttribute('method', 'post'); $this->setAttribute('enctype','multipart/form-data'); $this->add(array( 'name' => 'profilename', 'attributes' => array( 'type' => 'text', ), 'options' => array( 'label' => 'Profile Name', ), )); $this->add(array( 'name' => 'fileupload', 'attributes' => array( 'type' => 'file', ), 'options' => array( 'label' => 'File Upload', ), )); $this->add(array( 'name' => 'submit', 'attributes' => array( 'type' => 'submit', 'value' => 'Upload Now' ), )); } }
By that code above, we can call ProfileForm from action Controller :
// filename : module/Test/src/Test/Controller/ProfileController.php namespace Test\Controller; use Zend\Mvc\Controller\AbstractActionController; use Test\Model\Profile; class ProfileController extends AbstractActionController { public function addAction() { $form = new ProfileForm(); return array('form' => $form); } }
For view, we can write the following :
// filename : module/Test/view/test/profile/add.phtml $form = $this->form; $form->setAttribute('action', $this->url('Test/profile', //your route name ... array('controller'=>'profile', 'action' => 'add'))); $form->prepare(); echo $this->form()->openTag($form); echo $this->formRow($form->get('profilename')); echo $this->formRow($form->get('fileupload')); echo $this->formSubmit($form->get('submit')); echo $this->form()->closeTag();
Just that, and form will be created. How we filter the input ? we can create input filter by following :
// filename : module/Test/src/Test/Model/Profile.php namespace Test\Model; use Zend\InputFilter\Factory as InputFactory; use Zend\InputFilter\InputFilter; use Zend\InputFilter\InputFilterAwareInterface; use Zend\InputFilter\InputFilterInterface; class Profile implements InputFilterAwareInterface { public $profilename; public $fileupload; protected $inputFilter; public function exchangeArray($data) { $this->profilename = (isset($data['profilename'])) ? $data['profilename'] : null; $this->fileupload = (isset($data['fileupload'])) ? $data['fileupload'] : null; } public function setInputFilter(InputFilterInterface $inputFilter) { throw new \Exception("Not used"); } public function getInputFilter() { if (!$this->inputFilter) { $inputFilter = new InputFilter(); $factory = new InputFactory(); $inputFilter->add( $factory->createInput(array( 'name' => 'profilename', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 1, 'max' => 100, ), ), ), )) ); $inputFilter->add( $factory->createInput(array( 'name' => 'fileupload', 'required' => true, )) ); $this->inputFilter = $inputFilter; } return $this->inputFilter; } }
Now, we can set inputFilter to form from action controller, pass data post and file to form object, and check the validation :
// filename : module/Test/src/Test/Controller/ProfileController.php namespace Test\Controller; use Zend\Mvc\Controller\AbstractActionController; use Test\Model\Profile, Test\Form\ProfileForm; class ProfileController extends AbstractActionController { public function addAction() { $form = new ProfileForm(); $request = $this->getRequest(); if ($request->isPost()) { $profile = new Profile(); $form->setInputFilter($profile->getInputFilter()); $nonFile = $request->getPost()->toArray(); $File = $this->params()->fromFiles('fileupload'); $data = array_merge( $nonFile, //POST array('fileupload'=> $File['name']) //FILE... ); /** if you're using ZF >= 2.1.1 * you should update to the latest ZF2 version * and assign $data like the following $data = array_merge_recursive( $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray() ); */ //set data post and file ... $form->setData($data); if ($form->isValid()) { //HEY, FORM IS VALID... } } return array('form' => $form); } }
If form is valid, we can save file to directory we desired by \Zend\File\Transfer\Adapter\Http component, and add other validation, for example, add Size validation to validate minimal size will be accepted to be uploaded.
//import Size validator... use use Zend\Validator\File\Size; ......... if ($form->isValid()) { $size = new Size(array('min'=>2000000)); //minimum bytes filesize $adapter = new \Zend\File\Transfer\Adapter\Http(); //validator can be more than one... $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()){ $dataError = $adapter->getMessages(); $error = array(); foreach($dataError as $key=>$row) { $error[] = $row; } //set formElementErrors $form->setMessages(array('fileupload'=>$error )); } else { $adapter->setDestination(dirname(__DIR__).'/assets'); if ($adapter->receive($File['name'])) { $profile->exchangeArray($form->getData()); echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload; } } }
Finally, the complete controller source code :
// filename : module/Test/src/Test/Controller/ProfileController.php namespace Test\Controller; use Zend\Mvc\Controller\AbstractActionController; use Test\Model\Profile, Test\Form\ProfileForm; use Zend\Validator\File\Size; class ProfileController extends AbstractActionController { public function addAction() { $form = new ProfileForm(); $request = $this->getRequest(); if ($request->isPost()) { $profile = new Profile(); $form->setInputFilter($profile->getInputFilter()); $nonFile = $request->getPost()->toArray(); $File = $this->params()->fromFiles('fileupload'); $data = array_merge( $nonFile, array('fileupload'=> $File['name']) ); //set data post and file ... $form->setData($data); if ($form->isValid()) { $size = new Size(array('min'=>2000000)); //minimum bytes filesize $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()){ $dataError = $adapter->getMessages(); $error = array(); foreach($dataError as $key=>$row) { $error[] = $row; } $form->setMessages(array('fileupload'=>$error )); } else { $adapter->setDestination(dirname(__DIR__).'/assets'); if ($adapter->receive($File['name'])) { $profile->exchangeArray($form->getData()); echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload; } } } } return array('form' => $form); } }
You can separate File Transfer process in another function or model if you want. If Size validation failed, the form will show this :
References :
1.http://stackoverflow.com/questions/11690320/how-do-i-pass-file-and-post-data-into-a-form
2.http://zf2.readthedocs.org/en/latest/user-guide/forms-and-actions.html
[…] https://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ […]
Oh thanks man, you helped so much
You’re welcome 😉
Perfect, direct and easy, thanks @samsonasik.
You’re welcome 😉
nice work man
Thanks a lot man, you saved me a lot of time. stay blessed
you’re welcome
$adapter->setDestination(dirname(__DIR__).’/assets’);
thanks, but i don’t understand this destination.can you explain this please
it set the destination of upload files to module/Module_NAME/src/Module_NAME/assets.
I select the file to upload and click on the button but when I check the directory there is no file there. I’m using Zend Framework 2.4.2 . Please Help.
check the directory permissions, debug with error_reporting(E_ALL); and var_dump()
Thanks a lot! very helpful!!
You’re welcome
amazing tut
but need some help to rename uploaded file
in zf1
$file_upload_element->addFilter(‘Rename’, $newFileName);
how to do this in zf2
Rename filter is now under Zend\Filter\File namespace. so use like the following :
Thanks A lot .
Gazak Allah Khayran.
You’re welcome. Aamiin
Hello Samsonasik, I have a question. What is most recommend for save a file, a database or a folder in the filesystem? I need manage the file: overwrite, delete.
Thank you.
I recommend save a file in filesystem, save only a name of files in database.
Thank you from reply, some special motive for save in filesystem? and for delete it you would use the unlink function? 🙂 Greetings.
you should save something in database as small as possible to faster your query. for deleting, you can use what you want. unlink, shell_exec, system, etc.
back
if u have more than one file upload element u should specifiey in the valid like this otherwise u will get error that the other files not set
[php]
if (!$adapter->isValid($File[‘name’])){
[/php]
I have one thing in my mind why Zend Form isValid() not validating files
also the adapter to be included within file element and add validator add validation to adapter
I need to know what’s wrong on that ?
why it’s not implemented on ZF2 at least to be option
I think It should be implemented in ZF 2.1 , check this out https://github.com/zendframework/zf2/blob/develop/library/Zend/Form/Element/File.php . Hope it will be released soon
can i use it i have no problem to work with development one ?is File element ready or completed?
I’ve never tried it yet. you can clone ‘develop’ branch if you want from https://github.com/zendframework/zf2 with your git client.
Hi Samsonasik, first of all thanks for this great tut, its hard to find clean ones like this one, and secondly how about if i want to validate the extension, i still dont understand how to use ZF2 validators in the inputfilter
thank you!! great help 🙂
You’re welcome 😉
samsonasik, can you opt out me?
I think u have to wait zf 2.1
u will not imagine how easy it is to use file as inputfilter
try to download development version of zf from github and use it dont waste time with file\http adapter
Hi Abdul,
great tutorial, I am currently following this but keep getting
“Value is required and can’t be empty” when i try to submit the forms, where do you recomend me to start looking for errrors as I have not been able to track it down yet.
what zf2 version you are using ? i suggest to update to the latest release first.
try debug first
Thanks for a quick reply!
When I use this in add.phtml i ge t
“Fatal error: Uncaught exception ‘Zend\Form\Exception\DomainException’ with message ‘Zend\Form\Form::isValid is unable to validate as there is no data currently set’ in C:\..”
Any suggestions on next steps?
Once again thanks!
If you have a min spare it would be great if you could have a look, the code is available @
https://github.com/fwahlqvist/wdev-fileupload
Many Thanks
You have not yet made the assets folder in your ModuleName\src\ModuleName
Hi Abdul, I have created the assets folder in the root of the module but no luck, also when I use the debug as you suggested I get that the fileupload is empty But the value for the name is ok when I populate both a file a Nd the name.
Any further suggestions?
Ps will update my git tomorrow as I rewrote most of it to avoid namespace claches
Once again thanks
Fred
grab the sample module for sample upload from my github account : https://github.com/samsonasik/SanUpload , clone it. You’re welcome
Thanks Abdul, will do!
Best
Fred
You’re welcome
Hi Samsonasik,
I’m trying to upload the file in the “/public/images/” folder, but I can’t find the path I need to insert in the ->setDestination().
Could you help me?
Thanks Samsonasik, I’ve figure out that something was going wrong and I solved with
$string = ‘/../../../../../public/images/’;
$url = dirname(__FILE__).$string;
though I’m happy to use a more correct way.
And what if I’d like to rename the file before the upload is completed?
Thanks again, I’ve appreciated your help.
if you’re using ZendSkeletonApplication as basic skeleton. You should found :
and you should only write ‘./public/images’;
@somsonasik – great tutorial. Thanks so much.
I have been trying your extension validator code higher in the comments, but the validator fails. Looking at what gets passed to the extension validator it is a file with a .tmp extension, yet I pass a jpg. The tmp file is in the temp folder.
I pass the validator as follows.
$extensionvalidator = new Extension(array(‘extension’=>array(‘jpg’,’png’)));
$adapter -> setValidators( array($size, $count, $extensionvalidator ) , $file );
$file should be $file[‘Name’];
Thanks, I should have speciifed that I ended up moving the fileupload code into a model.
I pass the file name through a parameter called $file, but it should be the same as your script. For instance, I just checked the variable I passed in and I get the file name “181582878_full.jpg”.
I checked the isValid() method in extension validator and placed a called to echo $value to see what is passed in. It appears that the method is passed C:\Windows\Temp\php29D.tmp then fails as a tmp is not a jpg.
try to debug by assign a variable using reference.
$file = & $_FILES[‘fileupload’][‘name’] ;
I tried this and get the same response. Looking at the validator is passed two parameters and accepts only one. The way it is currently coded it will get passed the value of the .tmp file and the $_FILE array. Unfortunately as the .tmp file is passed first this cause the extension.php validator to fail. This looks like a bug to me, although I wonder if it could be an issue with the verison I am working off as it is obviously working for you. I will keep playing thanks for your help.
try another way. ZF 2.1 dev is now release. update your zf2 here https://github.com/zendframework/zf2 , and then, you can try https://github.com/cgmartin/ZF2FileUploadExamples for upload examples 😉
Hi….
I have followed steps as shown by you above,…
I can hit localhost/test/profile/add which gives me an error as “Route with name “Test” not found”
If I remove the action attribute, everything works fine.
Here is module.config.php
array(
‘routes’ => array(
‘home’ => array(
‘type’ => ‘segment’,
‘options’ => array(
‘route’ => ‘/’,
‘defaults’ => array(
‘controller’ => ‘Test\Controller\Profile’,
‘action’ => ‘add’,
),
),
),
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /application/:controller/:action
‘test’ => array(
‘type’ => ‘Literal’,
‘options’ => array(
‘route’ => ‘/test’,
‘defaults’ => array(
‘__NAMESPACE__’ => ‘Test\Controller’,
‘controller’ => ‘Profile’,
‘action’ => ‘add’,
),
),
‘may_terminate’ => true,
‘child_routes’ => array(
‘default’ => array(
‘type’ => ‘Segment’,
‘options’ => array(
‘route’ => ‘/[:controller[/:action]]’,
‘constraints’ => array(
‘controller’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
‘action’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
),
‘defaults’ => array(
),
),
),
),
),
),
),
‘controllers’ => array(
‘invokables’ => array(
‘Test\Controller\Profile’ => ‘Test\Controller\ProfileController’
),
),
‘view_manager’ => array(
‘template_path_stack’ => array(
‘test’ => __DIR__ . ‘/../view’,
),
),
);
your route name named ‘test’ not ‘Test’
Thanku 🙂
You’re welcome 😉
Hi,
I have one more question on namespace.
Here I have created profile controller as per ur post…
The name space used is Test\Controller
Folder structure goes like this – src/Test/Controller/ProfileController.php
What if I want to create new controller under src/Test/Controller/USerCOntroller.php??
How will the name space apply??
Can I use Test\Controller or should I use a different one??
you can use Test\Controller as __NAMESPACE__ in route.
I mean, in case of namespace Test\Controller I tried writing Test\PController..
when I hit test/profile/add , it gives me blank page
in module.config.php, where should I change the namespace implementation?
You should write Test\Controller\PController, not Test\PController
Can you give me an explanation ?? That makes me undertsand …since I m new to ZF2..
Do you mean my namspace should be Test\Controller\PController ??
As I have shown my module.config.php earlier, where does the namespace apply?
see dasprids presentation here : http://stuff.dasprids.de/slides/zendcon2012/introducing-the-new-zend-framework-2-router/presentation.html it will show you more detail.
OK. What about when the form is not valid because the Profile Name, for example, is required and user leave it blank, how can I save on the form the previously uploaded file so that it will not be uploaded again and again?
there is no deal for it for security reason. You should not save it until it verified.
What if there are many elements in a form, and the user only forgot one required element, and then in his second attempt he fills that element but then forgets to fill in the file input element, would it be good to save that input so that he will not forget to input that file again? Just analyzing on the user’s perspective. 🙂
Otherwise, I have found out that https://github.com/cgmartin/ZF2FileUploadExamples has that sample. Anyways, thanks @samsonasik
how i unlink the perticular image according to its name stored in database..please provide code for it…i know logic that select that field and unlink file bt in zend i dont know this.plz help….
saving file should be in filesystem. save name of file is on db. if you want to unlink, unlink the file, update selected rows of table.
Do you mind of writing a ZF 2.1+ tutorial for file upload? Could you include also tips of how can we do on the edit form with upload file?
you can read cgmartin repo : https://github.com/cgmartin/ZF2FileUploadExamples
I am getting this error. Array ( [fileUploadErrorIniSize] => File ” exceeds the defined ini size )
where as i am trying to upload a 85 Bytes size file. My default memory size in PHP.ini is 8M also when i apply this $this->setAttribute(‘enctype’,’multipart/form-data’);. I get Validation error that File upload field is required.
grab my sample code : https://github.com/samsonasik/SanUpload it should be work , if problem persist, i think it’s your apache problem.
how to fetch image from database in zend framewwork2 and which code i shall write in phtml file current i write
<img src="escapeHtml($user->image);?>”/> where $user is array and image is the field of database but i am not getting the image i get only name of the image which is in database
how to fetch image from database in zend framewwork2 and which code i shall write in phtml file current i write
<img src="escapeHtml($user->image);?>”/> where $user is array and image is the field of database but i am not getting the image i get only name of the image which is in database
you should save image name only in the db. for example : image.jpg saved in the db, save your file (image.jpg) in file system. and call by
i want upload a image. image uploading is working fine. but also want to display it after uploading . Suppose user goes to edit profile option means there old image should be display. when user uploading new image means it should be replaced. Please help me to do this
this is very easy. you just should save a filename to the db, placed the filename in the directory,and show it. for edit, delete old filename if upload new file, change current filename in db with uploaded filename.
Hi,
First of all thanks a lot for the explanation.
I need to upload files but I have formcollection,
so I get warnings about \Zend\File\Transfer\Adapter\Http() when it goes to file_exists() and it receives array ($value[“name] is received as array not as a path…)
I’ve previously build a simple form, and it works fine..what I have to change to make it work for the formcollection (every collection has file input…and maybe in the future I’d like to make it possible to add more file inputs to each of them )..
Thanks in advance.
Alona.
you can use cgmartin’s way : https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Form/CollectionUpload.php
in zf1, I simply put anything in Form file (like: FormUser.php):
+) create form
+) filter
+) validator
+) set destination
No thing in controller, in controller just call form.
In your tut I see many code in controller, so have we other way to do FORM UPLOAD, thanks !
check cgmartin’s form upload examples, there is a better way 😉 https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples
Thanks you very much, in this example you post above, I see the author using Input filter like below:
$inputFilter = new InputFilter\InputFilter();
// File Input
$file = new InputFilter\FileInput(‘file’);
$file->setRequired(true);
$file->getFilterChain()->attachByName(
‘filerenameupload’,
array(
‘target’ => ‘./data/tmpuploads/’,
‘overwrite’ => true,
‘use_upload_name’ => true,
)
);
$inputFilter->add($file);
But I often using input filter like:
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
‘name’ => ‘password’,
‘required’ => true,
‘filters’ => array(
array(‘name’ => ‘StripTags’),
array(‘name’ => ‘StringTrim’),
),
‘validators’ => array(
array(
‘name’ => ‘StringLength’,
‘options’ => array(
‘encoding’ => ‘UTF-8’,
‘min’ => 10,
‘max’ => 100,
),
),
),
)));
So, could you tell me how to do form upload follow second style. Thanks you !
you can follow my post ;). it’s just a choice about simplicity / flexibility.
salam samsonasik said
i hafe folow your tutorial it great work congratutation, i have implement multi fils upload and i want ask you if you can say me hoe to rename a fils? i use version zf2
chukran thanks
based on my post, you can do like the following :
but i recommend cgmartin’s way : https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Form/CollectionUpload.php , he is expert about it 😉
thank you soo mutch, was soo helpful
you’re welcome 😉
how can i get a name for a new file from:
$adapter->addFilter('File\Rename',
array('target' => dirname(__DIR__).'/assets/img.png',
'randomize' => true,
'overwrite' => true));
thany you for your replay.
but the result is : C:\…\module\Account\src\Account/assets/img.png
i think that i have change something
it print just img.png. 😦
i think the problem is when you’re using randomize and targetting, i’m not try it yet, i’ll look at it.
for now, i suggest to follow cgmartin’s way 😉
Hi,
@outman This would help you….
$adapter->setDestination(dirname(__DIR__).’/assets’);
foreach ($adapter->getFileInfo() as $info) {
$adapter->addFilter(‘File\Rename’,
array(‘target’ => $adapter->getDestination().’/newname.png’,
‘overwrite’ => true));
if ($adapter->receive($info[‘name’])) {
$filename = $adapter->getFileName();
echo $filename;
}
}
hello Abdul
How can I make multiple file uploads instead of single file.. I am using your project “SanUpload”, I am new to zend and need a little help.. thankyou
Thanks in Advance
try cgmartin’s examples : https://github.com/cgmartin/ZF2FileUploadExamples
I have been developing a signup form. ZF2 docs helped me much and some error helped me to reach here 😉
First of all, thanks very much. I implemented this and is working 😀
Few doubts:
1. I want the destination folder to be ‘/public/img/’. How to get base path in controller? (I thought files should be saved inside public. Please correct me if I am wrong)
2. I am using ZF 2.0, but
/** if you’re using ZF >= 2.1.1
* you should update to the latest ZF2 version
* and assign $data like the following
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
*/
if we are using this code, then what should be $File[‘name’] in
$adapter->setValidators(array($size), $File[‘name’]);
1. if you’re using skeleton application, you will find
in public/index.php which means Everything is relative to the application root now. so, you can set destination with
2.
ok, tnx again 😀
you’re welcome 😉
Hello,
To download the file uploded ?
try something like this in controller action :
Thx Bro,
I’m gone to try this 🙂
you’re welcome 😉
i had used your above article in that i need to add current time stamp to a uploaded file, can you help me in this
i am uploading .csv file how to give validation for upload only .csv file
Thank you for helping me,
can you help me for doing pagination using jquery
Hi, it’s possible to integrate this upload with Amazon S3 or is a totaly different system ?
I use the SDK AWS-PHP on gitub https://github.com/aws/aws-sdk-php and Uploadify or BlueImp System.
I tried to use this example but i don’t able to manage the Filter/Destination and putObject of Aws sdk.
Thanks in advance.
I’m not try yet, will take a look on it
Hi! Here’s a mistake when re-loading the form (when not passed validation) Help me please:
Fatal error: Uncaught exception ‘Zend\View\Exception\InvalidArgumentException’ with message ‘Array provided to Escape helper, but flags do not allow recursion’
How can I access the entire file name, including unique postfix, after it has been renamed? So I could save that name to database, which would be necessary for download.
I am uploading .csv file which contains 4 files(codeid(int), codename(varchar), codeper(decimal), staeid(int) )
1. how to check uploading file fields datatypes
2. in above 1,4 field are mandatory
[…] Abdul Malik Ikhsan’s Blog […]
Hi, Samsonasik.
How do you rename the files that you uploaded using zf2 2.2? (more than 1 document)
http://stackoverflow.com/questions/15781771/zf2-how-to-upload-files-more-than-1-file/17078862#17078862
It only rename the first file.
Cheers,
Zf2 Student
https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Form/CollectionUpload.php
$error = array();
foreach($dataError as $row)
{
$error = $row[];
}
$form->setMessages(array(‘upload’ => $error));
in this line $error = $row[];
Fatal error: Cannot use [] for reading in D:\root\xampp\htdocs\myproject\zendtest\module\Country\src\Country\Controller\CountryController.php on line 63
so how can i solve it…
i use ur all code
$error[] = $row;
thanks for reply 🙂
you’re welcome 😉
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size,$file[‘name’]));
error can display here
form is not valid
so what can i do…
all code can be copy past in ur site…
don’t copy paste! re-type ! :p
i have question. how to get the filename and path file in controller?i want send to the db table field with file(e.x image) path
How to validate multiple file upload
https://github.com/cgmartin/ZF2FileUploadExamples
hello.. i have one problem.. in the moment upload files exception message:
File:
/home/carcol/workspace/kaozend/vendor/zendframework/zendframework/library/Zend/File/Transfer/Adapter/AbstractAdapter.php:942
Message:
The given destination is not writeable
you must set permission to 777 the directory of destination.
i’m sorry, Thanks 😉
No prob. You’re welcome 😉
Hi samsonasik
i always get that my adapter is not valid.
[CODE]
public function save(array $data, $id = null){
if (!$form->isValid()) {
$this->setMessage(‘Please check your input!’);
return false;
}
$adapter = new \Zend\File\Transfer\Adapter\Http();
$File = $data[‘imageUpload’];
//tried without validator criterias
$adapter->setValidators(array(),$File[‘name’]);
if (!$adapter->isValid()){
echo ‘adapter not valid!’;
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
} //set formElementErrors
$form->setMessages(array(‘imageUpload’ => $error ));
} else {
echo ‘adapter is valid!’;
$adapter->setDestination(‘./public/img/’);
if ($adapter->receive($data[‘imageUpload’][‘name’])) {
echo ‘adapter reveive data!’;
$profile->exchangeArray($form->getData());
echo ‘Profile Name ‘.$profile->profilename.’ upload ‘.$profile->fileupload;
}else{
echo ‘adapter do not receive data!’;
}
}
//stopp here
die();
}
[/CODE]
I am using fileprg in the controller and then forward the prg to that save()-function, where i am doing the validation and image storing.
Do you have any suggestion on how to get that solved?
you forgot to initialize $form local variable.
Hi Sam,
thanks for your reply.
I did initialize the $form… just didnt paste it here…
$form = $this->getForm($mode);
$form->setData($data);
The form ant the data object do have all the data stored temporarly.. so i guess there must be somehting wrong with the adapters validation?
But i am not sure.
Ah, another thing. is there a way to put code in here formated like your posts and replies?
you should debug $data is. read this about posting code at wordpress http://en.support.wordpress.com/code/posting-source-code/
master 🙂 as I can modify the error messages? example:
Minimum expected size for file is ‘100MB’ but ‘1.69MB’ detected to:
Tamaño mínimo esperado para archivo es ‘100MB ‘pero ‘1 0.69 MB’ detecta
please read my post carefully, understand it! there is setMessages() func :p, print_r and debug it, btw, read the docs : http://zf2.readthedocs.org !
ok thanks 🙂
nice article but .. i have facing a problem like storing the files in file system…. as you said i tried with $adapter->setDestination(‘./public_adverts/images’); but it is working , i am using Zend 2 only… but the problem is .. later some days i will change my public_adverts folder to public only…. so how can i give the same dynamically.. otherwise is there any possible to give in configuration files. Please help me … i am very new to zend
you can read configuration from serviceManager, when you already write array config, you can call like the following :
Thanks for your reply . its helped me a lot … but i want to store that file in different sizes in different destinations. Can you guide me how to do it .. i tried with different ways but i didnt get solution. by this article i can add files in different destinations but i dont know how to resize it.. could you explain it.. thanks in advance .
you can resize with third party library, i like phpthumbnailer for its need.
Thanks for your reply.. i have one more doubt that … i want to store original image as well as rename image in filesystem, here i am using this code but by this i can save either original file or rename file only one at time … but i want to store both the files in single directory .. could you please explain how to solve this
$files->receive($front_advert_image[‘name’]);
$ramdom_filename = uniqid();
$files->addFilter(‘File\Rename’,array(‘target’ => $files->getDestination(‘front_advert_image’).’/’.$ramdom_filename.’.png’,’overwrite’ => true));
$files->receive($front_advert_image[‘name’]);
if (!$files->receive()) {
$messages = $files->getMessages();
echo implode(“\n”, $messages);
}
you can read “copy” function at phpmanual
can you explain little bit more ……………….
Hi Samsonasik,
In Edit Action, how can I bind the File Input with the previously uploaded file. Thanks in advance
it should be not, check the db, if exist, set required to false, and allow_empty to true, and to avoid confusion to user, show file uploaded as link to uploaded file, then user can choose to update the file or not.
How to edit means if i wana change the pic than?
it should be not, check the db, if exist, set required to false, and allow_empty to true, and to avoid confusion to user, show file uploaded as link to uploaded file, then user can choose to update the file or not.
I set the required field using previous field value
i want the output html like this
Male
Male
but when i echo the
echo $this->formRow($form->get(‘gender’));
its give me the output
male
female
hi samsonasik,
i have one question
$form->add(array(
‘type’ => ‘Zend\Form\Element\Radio’,
‘name’ => ‘gender’
‘options’ => array(
‘label’ => ‘What is your gender ?’,
‘value_options’ => array(
‘0’ => ‘Female’,
‘1’ => ‘Male’,
),
)
));
when i print this command echo $this->formRow($form->get(‘gender’)); it print the out put
like this
“Gender
Female
Male
”
now i want to the output like below
“Gender
Female
Male
“
create your custom view_helpers for formRow, formRadio, etc, and register under view_helpers key.read this for creating custom view helper : https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/
Dear sam,
Your post’s are very useful to me, can u help me in following problem ?
While validation i am getting this error : File ” was not uploaded
MY $data array
Array
(
[id_school] => 1
[submit] => Build my school
[Broucher] => Array
(
[name] => triggers_and_procedures.txt
[type] => text/plain
[tmp_name] => G:\xampp\tmp\php536A.tmp
[error] => 0
[size] => 670
)
)
and in my action
if($data[‘Broucher’][‘size’] > 0){
$size = new Size(array(‘max’=>5*(1024*1024)));
$extension = new \Zend\Validator\File\Extension(array(‘extension’ => array(‘docx’, ‘doc’,’pdf’,’xls’,’txt’)));
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size,$extension),$data[‘Broucher’][‘name’]);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$broucherError[] = $row;
}
}
}
After this i am getting above mentioned error in $broucherError
while uploading my file..i m getting these two error
Minimum expected size for file is ‘97.66kB’ but ‘107B’ detected
The given destination is not a directory or does not exist
how to minimize the size
$size = new Size(array(‘min’=>1000000));
if i enter primary value in form textbox then i submit the value that time it display the required dn’t use white space how can i implement that using filter or using jquery help me sir i want restrict the white space in form and at storage level.thanks for communicating with me your comments are really useful.
create your own validator for specific need, read the docs http://zf2.readthedocs.org/en/latest/modules/zend.validator.writing-validators.html
or you can use zend\validator\alnum : http://zf2.readthedocs.org/en/latest/modules/zend.validator.set.html#zend-validator-set-alpha-whitespace
how to upload the file into database
don’t do that. upload to filesystem, and save only the filename in db
in assets file r storing but file name is not storing to database,
i m proceeding with ur article only..
then just do insert filename into db , as a programmer, you can’t keep asking, you HAVE TO work hard, read the docs from the beginning for how to insert into database. As simple as that
thanks i will do
i am entering date format is 25-09-2003 in form that type is “date”.i am using doctrine i give the type=date.if i entering the value 25-09-2013 it’s give error on doctrine.that error is” Fatal error: Call to a member function format() on a non-object in C:\Apache\htdocs\proj\SMBERP\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\DateType.php on line 43″.how can solve that sir pls help.where i change the date format?
you have to google before ask :p, I just google and found the answet at the 1st page, read this http://akrabat.com/zend-framework-2/changing-the-format-of-a-zendform-datetime-element/
Could you please let me know what kind of changes you have implemented to resolve this?… I tried to solve it using link shared in below reply however that didn’t worked
i am using tabs with in form now i am submit the form at first tab text box fillout the validation is performed from
second tab because the second tab text box not entered so at submit time the tab is not go to another tab at
validation area how to go that validation tab at field requiring stage or how to set the focus at the required field.
help me
it is javascript area, use javascript! Use js lib like jQuery to easier your life.
thank you sir
hi sam sir now i want your help.i am using single form for two entities and add.phtml also single the contoller also single now how to bind the two entities in controller i am try this type $form->bind($department)->bind($designation);but it’s not work how can do this ?it’s possible are not sir?how to add to tables using single form help me.
Using Two Entity This Way $form->bind($value1);$form->bind($value2); U Can Bind Two Values in One Form..But main Question U Can Add One Form Value In Two Table??
My Input Filter Format is public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$fileInput = new InputFilter\FileInput(‘image-file’);
$fileInput->setRequired(true);
$fileInput->getValidatorChain()
->attachByName(‘filesize’, array(‘max’ => 20000000));
//->attachByName(‘fileimagesize’, array(‘maxWidth’ => 100, ‘maxHeight’ => 100))
//->attachByName(‘filemimetype’, array(‘mimeType’ => ‘image/png,image/x-png, image/jpeg,image/JPG’));
// $fileInput->getFilterChain( array(
// ‘target’ => ‘./public/data’,
// ‘randomize’ => false,
// ));
$fileInput->getFilterChain()->attachByName(
‘filerenameupload’,
array(
‘target’ => $this->_dir,
‘randomize’ => false,
‘use_upload_name’ => true,
‘overwrite’ => true,
‘use_upload_extension’ => true,
)
);
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
i Want To Convert This Format To Some think like
$inputFilter->add($factory->createInput(array(
‘name’ => ‘fupload’,
‘required’ => true,
‘filters’ => array(
),
‘validators’ => array(
array(
‘name’ => ‘filesize’,
‘options’ => array(
‘min’ => 1,
‘max’ => 20000000,
‘messages’ => array(
\Zend\Validator\NotEmpty::IS_EMPTY => ‘Code can not be empty.’
),),),
‘filerenameupload’ => array(
‘target’ =>’./public/data’,
‘randomize’ => false,
‘use_upload_name’ => true,
‘overwrite’ => true,
‘use_upload_extension’ => true,
),
),
)));
san you give correct syntax
please take a look cgmartin’s example : https://github.com/cgmartin/ZF2FileUploadExamples
Can U Give Me This Format In My Validation Code..
I Try This Format But Not Works..
$inputFilter->add($factory->createInput(array(
‘name’ => ‘fupload’,
‘required’ => true,
‘filters’ => array(
),
‘validators’ => array(
array(
‘name’ => ‘filesize’,
‘options’ => array(
‘min’ => 1,
‘max’ => 20000000,
‘messages’ => array(
\Zend\Validator\NotEmpty::IS_EMPTY => ‘Code can not be empty.’
),),),
‘filerenameupload’ => array(
‘target’ =>’./public/data’,
‘randomize’ => false,
‘use_upload_name’ => true,
‘overwrite’ => true,
‘use_upload_extension’ => true,
),
),
)));
Thank You Sir..i Follow Your Tutorial I Can Insert File In MY File manager and also i insert my data in my database with single form..thank you so much..:)
You’re welcome
i want to set the upload field as non required field can u help me..
‘required’ => false
I Try That But its not working..my code is
$inputFilter->add(
$factory->createInput(array(
‘name’ => ‘Fileupload’,
‘required’ => false
))
);
and alsoi write myvalidation codein my controller
$size = new Size(array(‘min’=>’0.001MB’,’max’=>’5.0MB’)); //minimum bytes filesize
$extensionvalidator = new \Zend\Validator\File\Extension(array(‘extension’=>array($_POST[‘fileformat’])));
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($extensionvalidator,$size,$req), $File[‘name’]);
//$adapter->setValidators(array($size), $File[‘name’]);
if (!$adapter->isValid())
add also ‘allow_empty’ => true ?
I Add ‘allow_empty’ => true in my input filter but still not working
the code is
$inputFilter->add(
$factory->createInput(array(
‘name’ => ‘Fileupload’,
‘required’ => false,
‘allow_empty’ => true
))
);
i think problem is here
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($extensionvalidator,$size,$req), $File[‘name’]);
//$adapter->setValidators(array($size), $File[‘name’]);
if (!$adapter->isValid())
i think yes, add if (!empty($File[‘name’])) to check before that 🙂
Thanks Thanks a lot..its working…:)
i need your database please help me…
Not working for me. It’s give an error “File not found” when i writer $file[‘name’] and when i write $file[‘tmp_name’] it show an error like “file is not uploaded” and above all it’s not add in my database
here i giving my code.
controller addAction.
public function addAction()
{
$dbAdapter = $this->getServiceLocator()->get(‘Zend\Db\Adapter\Adapter’);
$form = new SiteUserForm($dbAdapter);
$form->get(‘submit’)->setValue(‘Add’);
$request = $this->getRequest();
if ($request->isPost()) {
$nonFile = $request->getPost()->toArray();
$file = $this->params()->fromFiles(“vImage”);
$data = array_merge($nonFile, array(“vImage” => $file[‘tmp_name’]));
$user = new SiteUser();
$form->setData($data);
$form->setInputFilter($user->getInputFilter());
if ($form->isValid()) {
$user->exchangeArray($data);
$this->getSiteUserTable()->saveUser($user);
// Redirect to list of albums
return $this->redirect()->toRoute(‘user’);
}
}
return array(‘form’ => $form);
}
model
public function exchangeArray($data)
{
$this->vImage = (!empty($data[‘vImage’]))? $data[‘vImage’]:null;
$this->vAddress1 = (!empty($data[‘vAddress1’]))? $data[‘vAddress1’]:null;
}
I have not added any filter for image field.
so, please help me out to solve this issue.
Welcome sir,
I apply the example in a module i program now, I want to upload two files, The first upload right but the second give me an error message “File ‘021317.png’ was illegally uploaded. This could be a possible attack”
try cgmartin’s examples : https://github.com/cgmartin/ZF2FileUploadExamples
I solve the problem by using:
$adapter->isValid($file_input_name)
Thanks sir.
how to upload an image and video without creating a form? means directly open a box for selecting a file on click of text(upload image)
Hi! Thanks for your Posts,
I have a dude, How Can I Save It in a Different Module?
Ex.
Module Application/src/Application/Images->Save Here.
And
how can show the image in a different Module?..
Module Shows/Index-> Show Here.
It´s only images what i want to show but i suposs that this is with \Zend\File\Transfer\Adapter\Http();, But How?
Can You Give The Code Example.
since you’re using ZendSkeletonApplication, then your directory index is your application, so you should can got it by do :
Can You Show Me The Right Form To Show The Image, and the edit action for the file input element.
Pleas.
Can you do a post about how to create a CRUD with relationship tables in ZF2 and a field called image like this post and show it in the edit action, because i know that need diferents model and i dont know how to show in the edit action the data.
Please help me, please.
What do you think with this solution without the adapter:
if ($request->isPost()) {
$campaign = new Campaign();
$sm = $this->getServiceLocator();
$campaign->setServiceLocator($sm);
$File = $request->getFiles()->toArray();
$config = $this->getServiceLocator()->get(‘config’);
$destination = $config[‘path_img’][‘campaign_main_img’];
$filter = new Rename(array(
“target” => $destination.$File[‘path_main_image’][‘name’],
“randomize” => true,
));
$File[‘path_main_image’] = $filter->filter($File[‘path_main_image’]);
$post = array_merge_recursive(
$request->getPost()->toArray(),
$File
);
$form->setData($post);
if ($form->isValid()) {
$campaign->exchangeArray($form->getData());
$this->getCampaignTable()->saveCampaign($campaign);
return $this->redirect()->toRoute(‘campaign’, array(‘action’ => ‘list’));
}
}
Regards!
this is old post, the recommended way is cgmartin’s way : https://github.com/cgmartin/ZF2FileUploadExamples
[…] https://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ […]
Hi Samsonasik,
I would like to ask a question. In my registration form profile pic is not a mandatory field. If a user doesn’t select an image file, i would like to upload or set the mapping for a default file for it. For example as in facebook a default profile pic is displayed if no profile pic is set.
Any help would be appreciated….
add ‘required’ => false and/or ‘allow_empty’ => true.
I can’t have enough of it.
New recomendations here
http://framework.zend.com/manual/2.2/en/modules/zend.form.file-upload.html
thanks for pointing it 😉
file Upload progress Bar help me friends
hello , i am getting this error
Zend\Mvc\Router\Exception\RuntimeException
File:
D:\Program Files\ZendServer\data\libraries\Zend_Framework_2\2.2.1\library\Zend\Mvc\Router\Http\TreeRouteStack.php:313
Message:
Route with name “fileUpload” not found
read the error :p, you need to define “fileUpload” route 😛
when i run this code in my project it showing me the following error
Call to undefined method getRequest()
what should i do??
you need to add $this before it.
i use $this-> getRequest() but it showing me the same error
you need to start with skeleton app, and debug it, please do effort!
i started the skeleton app but found the same problem and i am using my own mvc not zend mvc.
and how can i destroy the session using zend session 2.3
Your code helped me. Thank you very much!
You should use “type” in the parent array not in the attribute array. In this way Zend recognize the form element correct (with enctype usw. see http://framework.zend.com/manual/2.3/en/modules/zend.form.file-upload.html#the-form-and-inputfilter)
$this->add(array(
‘name’ => ‘fileupload’,
‘type’ => ‘file’,
‘options’ => array(
‘label’ => ‘File Upload’,
),
));
How can i validate the type of file and its size????
Come on Samsonik, you are a good one with zf, but let me say that writing such a log of code it is not a simple file upload, that normally would take just 10 line of code in pure php.
how can you validate https://github.com/doctrine/DoctrineModule/blob/master/docs/validator.md ?
bagaimana kalau kita mengupload file dengan database..?
terima kasih mas..
file nya upload ke drive folder, namanya simpan di database.
dibuat pada controllernya mas..
kira2 perintahnya gimana mas?
terima kasih mas..
hmm..
ada gag mas tutorialnya yang menyimpannya didatabase terus nanti ketika kita mau lihat gambarnya muncul mas..?
maaf mas, banyak tanya..
terima kasih mas..
Hi, Sam!
I have the same problem as Vimal raj.
While validation i am getting this error : File ‘C:\xampp\tmp\php97DD.tmp’ could not be renamed. An error occurred while processing the file.
This is my Filter class.
$this->add(array(
‘name’ => ‘fileupload’,
‘required’ => true,
‘filters’ => array(
array(‘name’ => ‘\File\Rename’,
‘options’ => array(
‘source’ => ‘*’,
‘target’ => ‘/../../../../../public/img/photo.jpg’,
‘overwrite’ => true,
‘randomize’ => true,
),
),
),
‘validators’ => array(
array(
‘name’ => ‘\File\Size’,
‘options’ => array(
‘max’ => ’20Mb’,
),
),
array(
‘name’ => ‘\File\Extension’,
‘options’ => array(
‘extension’ => ‘jpg,gif,png’,
),
),
),
));
Could you help me with it?
hm.., maybe you can check cgmartin’s example for it : https://github.com/cgmartin/ZF2FileUploadExamples
I check this http://eliteinformatiker.de/2011/09/02/thumbnails-upload-and-resize-images-with-zend_form_element_file/
I use filter in my Constructor Class, not in Filter. Now I don’t understand how get new filename (renamed).
Hello Samsonasik,
First of all, thank you.
I’m learning ZF2 and you helped me a lot (realy a lot).
My project will soon be released, but I still have a problem with my images upload.
Upload is working fine but I don’t understand how I can reduce quality of JPG/PNG (idealy) before upload.
Any tips plz?
Kind regards,
Mat’
$request = $this->getRequest();
if ($request->isPost()) {
$project = new Projects();
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles(‘imageupload’);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$data = array_merge(
$nonFile,
array(‘imageupload’=> $File[‘name’])
);
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array(‘min’=>2000)); //minimum bytes filesize
$adapter->setValidators(array($size), $File[‘name’]);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array(‘imageupload’=>$error ));
} else {
$name=$project->name;
$newFile=’/’.$name.’.jpeg’;
$adapter->setDestination(‘module/Project/photo/’);
$adapter->addFilter(‘File\Rename’,
array(‘target’ => $adapter->getDestination().’/’.$newFile,
‘overwrite’ => true));
if ($adapter->receive($File[‘name’])) {
$file = $adapter->getFilter(‘File\Rename’)->getFile();
print_r($file[0][‘target’]);
}
}
}
}
i am unable to rename the file and save it in database without renaming im able to store as well as i folder.
you probably surplus the “/” after getDestination() because already in the newFile definition.
Hi Samsonasik,
Your tutorial worked perfectly for me but I’m stuck while display the images which are uploaded in data folder as I’m saving the images in data folder. I’m using virtual host which points to public folder. Please refer to the virtual host script
ServerAdmin admin@beatsboom
ServerName zf2-tutorial
DocumentRoot “E:\Nomaan\zf2_projects\zf2-tutorial\public”
ServerAlias http://www.zf2-tutorial
SetEnv APPLICATION_ENV “development”
ErrorLog “logs/zf2-tutorial-error.speck-error.log”
CustomLog “logs/zf2-tutorial-logs.speck-logs.log” common
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
Waiting for your reply & thanks in advance.
all asset will be relative to root folder of your app, so you should can call file_get_contents(“./data/file.ext’); , use header to set specific content type.
Thank you! Samsonasik for this post.
Hi Abdul Malik,
I saw your all the post but you never tried to implement blueimp with zf2. Actually I am trying to implement jQuery File Upload (blueimp) with zend framework 2.
I put all the js and css files inside public folder and trying to upload the files inside public folder. But unfortunately when I submit the Start upload button its giving below error
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
But my browser and server supports json, I have tested.
Its running fine when test for jQuery File Upload (blueimp) demo on my local server.
Please help me if you have any idea.
Any sample code or any help is fine.
Thanks in advance.
maybe you can try this : http://blog.alejandrocelaya.com/2014/11/29/file-uploads-with-zend-framework-2-and-jquery/
Hi Samsonasik,
Thank you for your help, I really appreciate your response. I already implemented that kind of solution but client is asking drag-drop and resize image kind of solution, like jQuery File Upload (blueimp), which I am unable to implement in my project. If you have any kind of solution. Please help me with that.
Thanking you again.
Dear Samsonasik,
Thank you so much for your wonderful tutorials! I have a problem. I have created an upload form with some other fields. When I click ‘Add’ the file name is sent to database and the file is saved in a file system. I also need to edit the fields. When I click the ‘Edit’ link, all the fields are filled but File upload field becomes empty. Could you please explain how to bring the uploaded file in an Edit form?
you should not fill upload field when do edit, change with existing data with ( image / link ) so you can decide to re-upload or make it empty.
Thank you for your reply. Still I am not clear yet. In this example, you have profile name and file upload. Suppose, you give a profile name and upload a file. Later, you need to change the profile name. When you click edit, change profile name and click upload now. Now, the the file upload becomes empty. My question is how to keep the uploaded file when we edit the profile name?? How to delete a file from a file system when an entry is deleted. Coding would be really helpful.
coffee ? 🙂 https://samsonasik.wordpress.com/buy-me-a-coffee/ …
it need more work. do effort. read the docs againts validation for free resource.
Chokrabe Akhii 7ayaaka llaah
Bagaimana kalau kita mau buat multiple upload y mas..? Pada bagian mana yang harus ditambahkan..?
coba cek https://github.com/cgmartin/ZF2FileUploadExamples
thank you very much for this tutorial, I follow it step by step, but I don’t know what is wrong!! the name of the file didn’t save in the database and also the file didn’t save in the folder system. any error was displayed!!!pleaise help
var_dump() it! debug it! I can’t help without the error
thanks for this tutorial , i have question …. how i can’t do messaging with zend framwork and thanks so match
messagging is nothing to do with any framework 😛
can you advice me what i do
hire me ? 😛
Hey bro can you tell me how to implement clint side validaton in a zend framework application
client side validation is nothing to do with zf, do javascript instead
THnaks bro
Hello samsonasik , thanks for the tutorial , am facing an issue in my application , when i sumbit the upload form i lost the $file name so i couldn’t add my picture name to my database this is my cose :
my add action in AlbumController.php :
public function addAction()
{
$form = new AlbumForm();
$form->get(‘submit’)->setValue(‘Add’);
$request = $this->getRequest();
if ($request->isPost())
{
$album = new Album();
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$album->exchangeArray($form->getData());
$this->getAlbumTable()->saveAlbum($album);
// Redirect to list of albums
return $this->redirect()->toRoute(‘album’);
}
}
return array(‘form’ => $form);
}
AlbumForm.php
$this->add(array(
‘name’ => ‘photo’,
‘type’ => ‘file’,
‘options’ => array(
‘label’ => ‘File Upload’,
),
));
Album.php
$inputFilter->add(
$factory->createInput(array(
‘name’ => ‘photo’,
‘required’ => true,
))
);
the line that i use to get form in my add.phtml:
echo $this->formRow($form->get(‘photo’));
any help or suggestion please;
Hello , problem fixed , thank you any way
hi. Thanks for awsome tutorial.
I am not able to uplad files to network folder in server. it would be great if you can helpme with uploading files to network folder. Thank you
Reblogged this on danleyb2.
When I call new \Zend\File\Transfer\Adapter\Http(), I see a bug from the __construct function. You can see the detail of this bug in this image: http://prntscr.com/aa7hyj . I’m using Zend Framework version 2.4.2.
“fileupload” is just an element name, the source of error is not there, please do effort!
how i can delete a file using zend framework plz anyone can tell
http://php.net/unlink
How can I do that in Zend Expressive?
composer require zendframework/zend-form :p
I am following all your posts and really thez are great to learn ZF2 , but I have stopped here to push a question :
I want to inject this upload way in an exist module , I have tried but 😦 .. so I guess my problem is in this file :
zend\module\Pizza\src\Pizza\Controller\PizzaController.php
public function addAction()
{
$add_form = new AddPizzaForm();
$request = $this->getRequest();
if($request->isPost())
{
$pizza = new Pizza();
$add_form->setInputFilter($pizza->getInputFilter());
// upload photo project
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles(‘fileupload’);
$datammn = array_merge(
$nonFile, //POST
array(‘fileupload’=> $File[‘name’]) //FILE…
);
//end for the upload photo project
$add_form->setData($request->getPost());
//set data post and file …
if($add_form->isValid())
{
// upload photo project
$size = new Size(array(‘min’=>2000000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
//validator can be more than one…
$adapter->setValidators(array($size), $File[‘name’]);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
} //set formElementErrors
$add_form->setMessages(array(‘fileupload’=>$error ));
} else {
$adapter->setDestination(‘./public/mmn’);
if ($adapter->receive($File[‘name’])) {
//$pizza->exchangeArray($add_form->getData());
//$this->getPizzaTable()->save($pizza);
$add_form->setData($datammn);
//echo ‘Profile Name ‘.$pizza->profilename.’ upload ‘.$pizza->fileupload;
}
}
//end for the upload photo project
$pizza->exchangeArray($add_form->getData());
$this->getPizzaTable()->save($pizza);
}
return $this->redirect()->toRoute(‘pizza’,array(‘action’=>’nasir’));
}
return array(‘form’ => $add_form);
}
is it possible to advice me 🙂 thanks a lot ..
you can try another sample by cgmartin: https://github.com/cgmartin/ZF2FileUploadExamples
// kalau ini kenapa ya mas, tidak bisa $adapter->receive?
$adapter->setDestination(PUBLIC_PATH.’/img/logo’); // .. /public/img/logo
$adapter->receive($files[‘image-file’]);
ketika saya print_r($adapter->getFileInfo());
[image-file] => Array
(
[name] => Screenshot from 2016-08-31 13:55:33.png
[type] => image/png
[tmp_name] => /tmp/phpEE3Y5g
[error] => 0
[size] => 176447
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[validated] => 1
// receive ?
[received] =>
[filtered] =>
[validators] => Array
(
[0] => Zend\Validator\File\Upload
)
[destination] => ../public/img/logo
)
mohon bimbingannya..
terima kasih..
coba set PUBLIC_PATH constant di public/index.php dengan absolute path ( dengan realpath(getcwd()))
your code is awesome, but i tried to follow your instruction every single step. why my file not want to switch to a predetermined place..?
return of $adapter->receive($File[‘name’]) always false. can you tell me
debug if folder as:
exists and writable.
How to store images in database using above program??
you should not store images in database, just store its file name ( path to file name).
OKAY THANK YOU
Using ZF3. After submiting file, constantly get: Fatal error: Class ‘Fantasy\Controller\Http’ not found error.
I guess you’re using new Http() directly in the class, make sure you add use statement :
“`php
use Zend\File\Transfer\Adapter\Http;
“`
or do direct with backslash prefix:
“`php
new \Zend\File\Transfer\Adapter\Http();
“`
If you don’t have the class in your vendor, make sure to require it via composer:
“`bash
composer require zendframework/zend-file
“`
Hi samsonasik,
I have two doubt,
The first one, I am using zend framework, I want confirm dialog box before user submit. If i use normal confirm box, it is not responding properly. please refer the below code…give solution.
<form action="form->getAction() ?>” method=”form->getMethod() ?>” class=”stdform stdform2″ id=”cash”>
form->employee_id ?>
form->ename ?>
……………….
$(document).ready(function(){
$(‘#cash’).form2json({success: function() {
location.href=”/donatecash/index”;
}
});
});
the second one is please refer below url.
http://stackoverflow.com/questions/42043094/datatables-warning-json-data-from-server-could-not-be-parsed-this-is-a-caused
please give any solution for this problems………Thank you
in zf1, you can disable layout and disable view rendering if it only needs a json, something like:
before echoing the json in action.