Prerequisites
This was implemented using ZendFramework 1.8.4.
On a standard ZendFramework Layout you want to upload a file (document) through a form to the server for later download.
Autoload it's enabled in this configuration, so i don't have to do the require call for the files. A folder "download" with write permission exists in the root of the public site.
The Form
The definition of the form is in personal library
class Personal_Form_DocumentForm extends Zend_Form { public function __construct($options = null) { parent::__construct($options); $this->setMethod('post'); $this->setAttrib('enctype', 'multipart/form-data'); $title = new Zend_Form_Element_Text('title'); $title->setLabel('Title'); $doc = new Zend_Form_Element_File('doc'); $doc->setLabel('Upload doc'); $doc->setDestination('download/')->setValueDisabled(true); $doc->addValidator('MimeType', false, array('text/plain', 'application/rtf')); $doc->addValidator('Count', false, 1); $doc->addValidator('Size', false, '10MB'); $this->addElements(compact('title','doc')); } }
The Controller
The form it's used in an action of a controller somewhere in the site (e.g. DocumentController witch extends Zend_Controller_Action )
public function createAction(){ $addDocumentForm = new Personal_Form_DocumentForm(); $this->view->addDocumentForm = $addDocumentForm; //put an Add button to the form $addDocumentForm->addElement('submit', 'Add'); // Save document if ($this->getRequest()->isPost()) { $postData = $this->getRequest()->getPost(); $valid = $addDocumentForm->isValid($postData); if (!$valid) return; $values = $addDocumentForm->getValues(); //you could add here some logic to save an entry to database //we save the file with the initial name from the client converted to //an url friendly format preceded by a random number $file = mt_rand(10,999) . '_'. urlencode($values['doc']); $element = $addDocumentForm->getElement('doc'); //use 'overwrite' to overwrite a file with the same name, by default //will give an error in this case $element->addFilter('Rename',array('target' => 'download/' . $file )); if ($element->receive()) { $this->view->message = "File uploaded at " . $file ; }else{ $this->view->message = print_r($element->getMessages(), true); } } }
The View
In the view put:
echo $this->addDocumentForm; echo isset($this->message)?$this->message:"";