Uploading a file using Zend Framework is really easy and requires just a few steps of code to get it to work. It is even easier in the newer releases where the order of how to process form data has been solved.
The first thing to to in order to have the upload display as a browse button is to extend the form with an input field for a file upload. This can be done by creating a new form element.
$uploadFile = new Zend_Form_Element_File('uploadFile');
$uploadFile->setLabel('Attach file')
->setDestination(APPLICATION_PATH.'/../data/original');
This will create a form tag in HTML as:
<form id="uploadImageForm" enctype="multipart/form-data" method="post" class="form-horizontal" action="/productmanager/product/uploadImage/id/15978">
The upload input object generated is.
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" id="MAX_FILE_SIZE"> <input type="file" name="uploadFile" id="uploadFile">
There are additional settings that can be specified on the upload form to limit size of file, mime type or file extension accepted. See more details about that in the Zend Framework online reference.
In the Controller, you just need to process the form as usual by getting the values and then receiving of the new file will be to the target directory specified in the setDestination() method of the form element. If you don't want to decide directory in the form class, it can be set after creating the form in the controller too.
Setting the destination in the controller
$form = new Application_Form_UploadImageForm(); $form->uploadFile->setDestination(APPLICATION_PATH.'/../data/original');
Receiving the file
if ($testForm->isValid($this->_request->getPost())) {
// Receive values
$values = $form->getValues();
try {
$form->uploadFile->receive();
Zend_Debug::dump($form->uploadFile->getFileName());
} catch (Zend_File_Transfer_Exception $e) {
echo $e->message();
}
}
When the form is processed, the file is uploaded using it's original name in the folder specified as Destination.
