Zend 框架有一种更好、更安全的方法......
创建帮助类来检索文件扩展名。.
类图像上传 {
public function getExtension ($name)
{
if($name){
foreach ($name as $val){
$fname=$val['name'];
}
$exts = split("[/\\.]", $fname) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
}
}
在控制器中:
类 ProfileController 扩展 Zend_Controller_Action { function indexAction() { $this->view->title = "Profile"; $this->view->bodyCopy = "
请填写此表格。
";
$form = new ImgForm();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->setDestination('images/users/big');
// getting extension
$filename = $adapter->getFileInfo();
$uhelper = new ImageUpload; // cals for help to get file extension
$extension = $uhelper->getExtension($filename); // got extension
// success -- file handled
//rename
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
$adapter->addFilter('Rename', array('target' => 'images/users/big/'.$identity->id.'.'.$extension,
'overwrite' => true));
if (!$adapter->receive()) {
$form->addError($adapter->getMessages());
}
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
}
当你的表格应该是:
parent::__construct($options);
$this->setName('upload');
$this->setAttrib('enctype', 'multipart/form-data');
$file = new Zend_Form_Element_File('file');
$file->setLabel('File')
->addValidator('Count', false, 1) // ensure only 1 file
->addValidator('Size', false, 102400) // limit to 100K
->addValidator('Extension' ,false, 'jpg,png,gif') // only JPEG, PNG, and GIFs
->setRequired(true);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Upload');
$this->addElements(array($file, $submit));
}
}
玩得开心