我使用Zend Form并上传文件。我需要为它重命名和用户addFilter。但是,如果我尝试在代码中获得文件的扩展名,我会收到错误“文件太多,允许最大'1'但是给出'2'”。如果我尝试使用$ _FILES进行扩展,看起来它可以解决但看起来很难看。你能告诉我如何重命名文件保存它的扩展名吗?
$form = new Form_ImportSubscribers();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
//it looks like it works but it's ugly solution
// $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
//causes an error "Too much files, maximum '1' are allowed but '2' are given"
$extension = pathinfo($form->file->getFileName(), PATHINFO_EXTENSION);
$form->file->addFilter('Rename', $accountId . '_' . time() . '.' . $extension);
if (!$form->file->receive()) {
$this->view->form = $form;
$this->view->listName = $list->list_name;
return;
}
答案 0 :(得分:14)
如果$ form-> file-> getFileName()返回多个值,我假设你上传了多个文件。在这种情况下,您可以应用重命名过滤器并接收单个文件,如下所示:
/*@var $adapter Zend_File_Transfer_Adapter_Http */
$adapter = $form->file->getTransferAdapter();
$receivingOK = true;
foreach ($adapter->getFileInfo() as $file => $info) {
$extension = pathinfo($info['name'], PATHINFO_EXTENSION);
$adapter->addFilter('Rename', $accountId . '_' . time() . '.' . $extension, $file);
if (!$adapter->receive($file)) {
$receivingOK = false;
}
}
if (!$receivingOK) {
$this->view->form = $form;
$this->view->listName = $list->list_name;
return;
}
即使您不执行多个文件上传,它也应该工作。
答案 1 :(得分:2)
这是我在控制器中的代码,它适用于Zend 1.11:
$uploadForm = new Application_Form_DeckblattUpload();
$front = $uploadForm->getElement('front');
/* @var $front Zend_Form_Element_File */
$tfa = $front->getTransferAdapter();
/* @var $tfa Zend_File_Transfer_Adapter_Abstract */
$tfa->addFilter('Rename', array(
'target' => APPLICATION_PATH .'/public/dir/somepath.jpg',
'overwrite' => true));
$back = $uploadForm->getElement('back');
/* @var $front Zend_Form_Element_File */
$tfa = $back->getTransferAdapter();
/* @var $tfa Zend_File_Transfer_Adapter_Abstract */
$tfa->addFilter('Rename', array(
'target' => APPLICATION_PATH . '/public/someOtherDir/somepath.jpg',
'overwrite' => true));
if ($this->getRequest()->upload) {
if ($uploadForm->isValid($this->getRequest()->getParams())) {
$uploadForm->getValues(); //<- this does the uploading
//Success-Message
}
else {
//Failure-Message
}
}
$this->view->uploadForm = $uploadForm;
表单只包含2个Zend_Form_Elements_Files(“后退”和“前面”)和提交按钮(“上传”)。
我希望这可以让您了解如何使用重命名过滤器并仍然使用$ form-&gt; isValid()。不要混淆http://framework.zend.com/manual/en/zend.file.transfer.filters.html和http://framework.zend.com/manual/en/zend.filter.input.html
另请注意,您不能在装饰器中使用'viewHelper'作为文件元素。而是使用'文件'。希望这仍然有帮助。
答案 2 :(得分:1)
尝试使用以下内容:
$upload = new Zend_File_Transfer();
// use setDestination, addValidator etc
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
$file = '/path/to/file/name.ext';
$upload->addFilter('Rename', $file);
//Do rest of code
}
$upload->receive();