//excerpt
$file = new Zend_Form_Element_File(\'file\');
$file->setLabel(\'File to upload:\')
->setRequired(true)
->addValidator(\'NotEmp
Easy fix to get Zend to rename before uploading
The problem I address here is explained in more detail here: http://www.thomasweidner.com/flatpress/2009/04/17/recieving-files-with-zend_form_element_file/
I was having trouble getting the file to rename before uploading and found the solution for my scenario. At some point Zend thought it clever to have the getValue() method of the file element upload the file for you. Fortunately they added an option to disable this feature.
Solution: If you are calling getValue() on the file element, or getValues() on the form, and you want to modify the name before it uploads you have to set setValueDisabled(true) on your Zend_Form_Element_File.
Fyi: I don't claim this to be optimized, I just claim it to work for me
Creating the form element (magic inside)
$uploadConfig = Zend_Registry::get('upload');
$fileuploader = new Zend_Form_Element_File('ugc_fileupload');
$fileuploader->setRequired(true);
$fileuploader->setLabel('*Upload File:');
$fileuploader->addValidator('Count', false, 1); // ensure only 1 file
$fileuploader->setValueDisabled(true); // ***THIS IS THE MAGIC***
$fileuploader->addValidator('Size', false, $uploadConfig['videomax']);
$fileuploader->addValidator('Extension', false, 'mov, avi, wmv, mp4');
$this->addElement($fileuploader, 'ugc_fileupload');
Rename before uploading (inside preUpload($form))
$uploadCfg = Zend_Registry::get('upload');
// Get the parts of the name
// Call to getValue() here was uploading the file before telling it not to!
$atiFile = $form->ugc_fileupload->getValue();
$fileExt = $this->getFileExtension($atiFile);
$nameBase = $this->getFileName($atiFile, $fileExt);
$fullName = $atiFile;
$fullPath = $uploadCfg['tmpdir'] . $fullName;
// Keep checking until the filename doesn't exist
$numToAdd = 0;
while(file_exists($fullPath)) {
$fullName = $nameBase . $numToAdd . $fileExt;
$fullPath = $uploadCfg['tmpdir'] . $fullName;
$numToAdd++;
}
$upload = new Zend_File_Transfer_Adapter_Http();
// or $upload = $form->ugc_fileupload->getTransferAdapter();
// both work, I'm not sure if one is better than the other...
//Now that the file has not already been uploaded renaming works
$upload->addFilter(new Zend_Filter_File_Rename(array(
'target' => $fullPath,
'overwrite' => false)
));
try {
$upload->receive();
} catch (Zend_File_Transfer_Exception $e) {
//$e->getMessage()
}
Helper methods
public function getFileName($path, $ext) {
return $bname = basename($path, $ext);
}
public function getFileExtension($path) {
return $ext = strrchr($path, '.');
}