1

这是我的表格

class Admin_Form_RoomtypeForm extends Zend_Form
{
    public function init()
    {

       $name = new Zend_Form_Element_Text('name');
       $name->setLabel('Name :');

       $imagePath = '/home/dinuka/image';

       $image = new Zend_Form_Element_File('image');
       $image->setLabel('Image URL :');
       $image->setDestination($imagePath);
       $image->addValidators(array(array('IsImage', false)));

       $submit = new Zend_Form_Element_Submit('submit');

       $this->addElements(array($name, $image, $submit));
   }
}

这是我的控制器

class Admin_RoomtypesController extends Zend_Controller_Action 
{
    public function addAction()
    {
         $form = new Admin_Form_RoomtypeForm();

         if ($this->getRequest()->isPost()) {
              $formData = $this->getRequest()->getPost();
              $form->populate($formData);       

              $name = $form->getValue('name');

         }
    }
}

现在我想在将文件名更改为 $name 值后上传文件。我该怎么做?

4

2 回答 2

0

我必须为我的一个项目做这样的事情,除了我需要唯一的文件名。这不是一个完美的解决方案,但它可能会让您走上正轨:

<?php
class My_Filter_UniqueFilename implements Zend_Filter_Interface
{
  public function filter($value)
  {
    $upload_dir = pathinfo($value, PATHINFO_DIRNAME);
    $ext = pathinfo($value, PATHINFO_EXTENSION);
    $filename = $upload_dir . "/" . md5(microtime()) . "." . $ext;
    $result = rename($value, $filename);

    if($result === true) {
    return $upload_dir . $filename;
    }

    require_once 'Zend/Filter/Exception.php';
    throw new Zend_Filter_Exception(sprintf("File '%s' could not be renamed. An error occured while processing the file.", $value));
  }
}

于 2011-08-17T01:27:48.250 回答
0

最后我做了如下。

-形式 -

class Admin_Form_RoomtypeForm extends Zend_Form
{
    public function init()
    {

       $name = new Zend_Form_Element_Text('name');
       $name->setLabel('Name :');

       $image = new Zend_Form_Element_File('image');
       $image->setLabel('Image URL :');           
       $image->addValidators(array(array('IsImage', false)));

       $submit = new Zend_Form_Element_Submit('submit');

       $this->addElements(array($name, $image, $submit));
   }
}

-控制器 -

class Admin_RoomtypesController extends Zend_Controller_Action 
{
    public function addAction()
    {
         $form = new Admin_Form_RoomtypeForm();

         if ($this->getRequest()->isPost()) {
              $formData = $this->getRequest()->getPost();
              $form->populate($formData);       

              $name = $form->getValue('name');
              $image = $form->getValue('image');

              $temp = explode(".", $image);
              $ext = $temp[count($temp)-1];

              $imageName = $name .'.'. $ext;

              $fullPath  = $imagePath ."/". $imageName; 
              copy("/tmp/". $image, $fullPath);    
         }
    }
}

默认图像上传到 /tmp 文件夹。我们可以使用setDestination()方法作为我的示例来更改它。

谢谢大家

于 2011-12-16T10:23:05.007 回答