我使用Zend Framework 1.9.6.我想我已经有很多的想法,除了最后.这是我到目前为止
形成:
<?PHP class Default_Form_UploadFile extends Zend_Form { public function init() { $this->setAttrib('enctype','multipart/form-data'); $this->setMethod('post'); $description = new Zend_Form_Element_Text('description'); $description->setLabel('Description') ->setrequired(true) ->addValidator('NotEmpty'); $this->addElement($description); $file = new Zend_Form_Element_File('file'); $file->setLabel('File to upload:') ->setrequired(true) ->addValidator('NotEmpty') ->addValidator('Count',false,1); $this->addElement($file); $this->addElement('submit','submit',array( 'label' => 'Upload','ignore' => true )); } }
控制器:
public function uploadfileAction() { $form = new Default_Form_UploadFile(); $form->setAction($this->view->url()); $request = $this->getRequest(); if (!$request->isPost()) { $this->view->form = $form; return; } if (!$form->isValid($request->getPost())) { $this->view->form = $form; return; } try { $form->file->receive(); //upload complete! //...what now? $location = $form->file->getFileName(); var_dump($form->file->getFileInfo()); } catch (Exception $exception) { //error uploading file $this->view->form = $form; } }
现在我该怎么做文件?默认情况下已将其上传到我的/ tmp目录.显然这不是我想要保留的地方.我希望我的应用程序的用户能够下载它.所以,我认为这意味着我需要将上传的文件移动到我的应用程序的公共目录,并将文件名存储在数据库中,以便我可以将其显示为一个url.
解:
我决定将上传的文件放入数据/上传(这是一个到我应用程序之外的目录的sym链接,以便使我的应用程序的所有版本都可以访问).
# /public/index.PHP # Define path to uploads directory defined('APPLICATION_UPLOADS_DIR') || define('APPLICATION_UPLOADS_DIR',realpath(dirname(__FILE__) . '/../data/uploads')); # /application/forms/UploadFile.PHP # Set the file destination on the element in the form $file = new Zend_Form_Element_File('file'); $file->setDestination(APPLICATION_UPLOADS_DIR); # /application/controllers/MyController.PHP # After the form has been validated... # Rename the file to something unique so it cannot be overwritten with a file of the same name $originalFilename = pathinfo($form->file->getFileName()); $newFilename = 'file-' . uniqid() . '.' . $originalFilename['extension']; $form->file->addFilter('Rename',$newFilename); try { $form->file->receive(); //upload complete! # Save a display filename (the original) and the actual filename,so it can be retrieved later $file = new Default_Model_File(); $file->setDisplayFilename($originalFilename['basename']) ->setActualFilename($newFilename) ->setMimeType($form->file->getMimeType()) ->setDescription($form->description->getValue()); $file->save(); } catch (Exception $e) { //error }
默认情况下,文件将上传到系统临时目录,这意味着您可以:
>使用move_uploaded_file
将文件移动到别的地方,
>或配置Zend Framework应移动文件的目录;你的form元素应该有一个setDestination方法,可以使用它.
第二点,the manual有一个例子:
$element = new Zend_Form_Element_File('foo'); $element->setLabel('Upload an image:') ->setDestination('/var/www/upload') ->setValueDisabled(true);
(但阅读该页面:还有其他有用的信息)