在zend框架中创建个人资料图片上传器

时间:2011-07-12 07:32:58

标签: php zend-framework

我最近开始研究zend框架。我想上传个人资料图片并重命名&重新调整它的大小。我使用下面的代码。这可以上传,但我无法重命名,也没有办法重新调整上传文件的大小。

如果($这 - > Request()方法 - > isPost())             {

            if(!$objProfilePictureForm->isValid($_POST))
            {
                //return $this->render('add');

            }

            if(!$objProfilePictureForm->profile_pic->receive())
            {
                $this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';


            }

            if($objProfilePictureForm->profile_pic->isUploaded())
            {
                $values = $objProfilePictureForm->getValues();
                $source = $objProfilePictureForm->profile_pic->getFileName();


                //to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.

                $new_image_name = 'new';

                //save image to database and filesystem here
                $image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
                if($image_saved)
                {
                    $this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
                    $objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
                }
            }
        }

1 个答案:

答案 0 :(得分:3)

要在上传时重命名文件,您必须将“重命名过滤器”添加到file-form-element。该类称为Zend_Filter_File_Rename

// Create the form
$form = new Zend_Form();

// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);

// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');

// Process postdata
if($this->_request->isPost())
{
    // Get the file and store it within the specified destination with the specified name.
    $file->receive();
}

要动态创建文件名,您可以使用时间戳或其他名称命名。您也可以在调用$file->receive()之前在后数据处理中应用重命名过滤器。如果您在表中插入一行并希望使用刚刚插入的行的id命名该文件,这可能很有用。

由于您想要存储个人资料图片,您可以从您的数据库中获取该用户的ID,并使用该ID命名该图片。