问题
This is my form
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));
}
}
This is my controller
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');
}
}
}
Now i want to upload file after change file name as $name value. How can i do it?
回答1:
I had to do something like this for one of my projects, except i needed unique filenames. This isn't a perfect solution, but it may put you on the right track:
<?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));
}
}
回答2:
Finally I done it as following.
-Form -
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));
}
}
-Controller -
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);
}
}
}
default image is upload to /tmp folder. We can change it using setDestination()
method as my example.
Thank for All
来源:https://stackoverflow.com/questions/6435569/file-upload-after-rename-the-file-in-zend