Monday, May 2, 2011

How to rename a file uploaded with Zend_Form_Element_File

How to rename a file uploaded with Zend_Form_Element_File

There are several ways of renaming files if you don’t want to use Zend_Form_Element component. However, the following is a ZF technique.Suppose you have a very basic form with a single file element:

Form.php
class My_Form extends Zend_Form { 
public function init()     { 
$element = new Zend_Form_Element_File('imagefile'); 
$element->setLabel('Upload an image:'); 
$element->setDestination($uploaddir); 
/* file directory */ 
$element->addValidator('Count', false, 1);    
$element->addValidator('Size', false, 202400);    
$element->setRequired(false); 
$element->addValidator('IsImage', false, 'jpeg,jpg,png,gif'); 
$this->addElement($element, 'imagefile'); 
} 
}
 
What you need to do is to override the isValid( .. ) method of your Form Object:

Form.php
public function isValid($data) { 
$oldname = pathinfo($this->imagefile->getFileName());    
$newname = $this->getUniqueCode(10) . '.' . $oldname['extension'];    
$this->imagefile->addFilter('Rename',$newname);    
return parent::isValid($data);      
}
 
If you don’t want to loose your other validators , don’t forget to call the parent isValid() method . As you can see, I used PHP’s pathinfo() method to parse the file path. (There should be another one in ZF ). I renamed it with a string of 10 random characters, and kept the extension as it was. Below is the method that you can use for the random file name :

function getUniqueCode($length = "") {     
$code = md5(uniqid(rand(), true));    
if ($length != "")  return substr($code, 0, $length); 
else   return $code; 
}
Finally, in your controller, you basically check if the form is valid,

MyFormController.php
$request = $this->getRequest();  
$form  = new My_Form(); 
if ($request->isPost()) { 
if ($form->isValid($request->getPost())) { 
$formData = $form->getValues(); 
try {      $form->imagefile->receive();    } 
catch (Exception $e) {     throw new Zend_Exception ('There is a problem with the file upload');        } 
}  }
 
I hope it helps.

0 评论:

Post a Comment