【问题标题】:Zend Framework: image uploadZend Framework:图片上传
【发布时间】:2009-12-08 16:32:47
【问题描述】:

我想上传一张 Zend Framework 1.9.6 版的图片。上传本身工作正常,但我还想要一些其他的东西......我完全卡住了。

  • 不会显示未能上传图片的错误消息。
  • 如果用户未输入所有必填字段但已上传图像,那么我想在表单中显示上传的图像。作为图像或图像的链接。只是对用户的某种形式的反馈。
  • 我想使用 Zend_Validate_File_IsImage。但它似乎没有任何作用。
  • 最后;是否有一些自动重命名功能?

非常欢迎所有想法和建议。我已经挣扎了两天了。

这些是简化的代码sn-ps:

myform.ini

method = "post"

elements.title.type = "text"
elements.title.options.label = "Title"
elements.title.options.attribs.size = 40
elements.title.options.required = true

elements.image.type = "file"
elements.image.options.label = "Image"
elements.image.options.validators.isimage.validator = "IsImage"

elements.submit.type = "submit"
elements.submit.options.label = "Save"

TestController

<?php
class Admin_TestController extends Zend_Controller_Action
{
  public function testAction ()
  {
    $config = new Zend_Config_Ini(MY_SECRET_PATH . 'myform.ini');
    $f = new Zend_Form($config);

    if ($this->_request->isPost())
    {
      $data = $this->_request->getPost();

      $imageElement = $f->getElement('image');
      $imageElement->receive();

      //$imageElement->getValue();

      if ($f->isValid($data))
      {
        //save data
        $this->_redirect('/admin');
      }

      else
      {
        $f->populate($data);
      }
    }

    $this->view->form = $f;
  }
}
?>

我的观点只是回应了“表单”变量。

【问题讨论】:

    标签: php zend-framework file-upload


    【解决方案1】:

    首先,将其放在脚本的开头:

    error_reporting(E_ALL);//这应该显示所有的php错误

    我认为表单中缺少错误消息,因为您在显示表单之前重新填充了它。我认为这会消除任何错误消息。要解决此问题,请删除此部分:

    else
    {
       $f->populate($data);
    }
    

    要在表单中显示上传的图片,只需在视图模板中添加一个 div,如下所示:

    <div style="float:right"><?=$this->image?></div>
    

    如果图片上传成功,则使用 img 标签填充 $view->image。

    至于自动重命名,不,它不是内置的,但很容易。我会在下面告诉你怎么做。 以下是我处理图片上传的方式:

    $form = new Zend_Form();
    $form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
    
    $image = new Zend_Form_Element_File('image');
    $image->setLabel('Upload an image:')
          ->setDestination($config->paths->upload)
          ->setRequired(true)
          ->setMaxFileSize(10240000) // limits the filesize on the client side
          ->setDescription('Click Browse and click on the image file you would like to upload');
    $image->addValidator('Count', false, 1);                // ensure only 1 file
    $image->addValidator('Size', false, 10240000);            // limit to 10 meg
    $image->addValidator('Extension', false, 'jpg,jpeg,png,gif');// only JPEG, PNG, and GIFs
    
    $form->addElement($image);
    
    $this->view->form = $form;
    
    if($this->getRequest()->isPost())
    {
        if(!$form->isValid($this->getRequest()->getParams()))
        {
            return $this->render('add');
        }
    
        if(!$form->image->receive())
        {
            $this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
            return $this->render('add');
        }
    
        if($form->image->isUploaded())
        {
            $values = $form->getValues();
            $source = $form->image->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 = 'someNameYouInvent';
    
            //save image to database and filesystem here
            $image_saved = move_uploaded_file($source, '/www/yoursite/images/'.$new_image_name);
            if($image_saved)
            {
                $this->view->image = '<img src="/images/'.$new_image_name.'" />';
                $form->reset();//only do this if it saved ok and you want to re-display the fresh empty form
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      首先,看看Quick Start 教程。注意它是如何有一个 ErrorController.php 来为你显示错误信息的。还要注意 application.ini 有这些行如何导致 PHP 发出错误消息,但请确保您在“开发”环境中查看它们(在 public/.htaccess 中设置)。

      phpSettings.display_startup_errors = 1
      phpSettings.display_errors = 1
      

      其次,ZF 有一个文件上传的重命名过滤器:

      $upload_elt = new Zend_Form_Element_File('upload');
      $upload_elt
      ->setRequired(true)
      ->setLabel('Select the file to upload:')
      ->setDestination($uploadDir)
      ->addValidator('Count', false, 1) // ensure only 1 file
      ->addValidator('Size', false, 2097152) // limit to 2MB
      ->addValidator('Extension', false, 'doc,txt')
      ->addValidator('MimeType', false, 
                     array('application/msword',
                       'text/plain'))
      ->addFilter('Rename', implode('_', 
                        array($this->_user_id,
                          $this->_upload_category,
                          date('YmdHis'))))
      ->addValidator('NotExists', false, $uploadDir)
      ;
      

      上面的一些有趣的事情:

      • 根据需要标记上传(您的 .ini 似乎没有这样做)
      • 将所有上传文件放在一个特殊目录中
      • 限制文件大小和可接受的 mime 类型
      • 将上传重命名为 myuser_category_timestamp
      • 不要覆盖现有文件(不太可能,鉴于我们的时间戳方案,但无论如何都要确保)

      所以,以上内容符合您的要求。在接收上传的控制器/动作中,您可以这样做:

      $original_filename = $form->upload->getFileName(null, false);
      if ($form->upload->receive()) {
        $model->saveUpload(
          $this->_identity, $form->upload->getFileName(null, false),
          $original_filename
        );
      }
      

      请注意我们在执行接收()之前如何捕获 $original_filename(如果需要)。在我们 receive() 之后,我们执行 getFileName() 来获取重命名过滤器选择的新文件名。

      最后,在 model->saveUpload 方法中,您可以将任何内容存储到数据库中。

      【讨论】:

        【解决方案3】:

        确保您的视图还输出您在控制器中生成的任何错误消息:加载错误、字段验证、文件验证。重命名将是您的工作,其他后期处理(例如 image-magick convert)也是如此。

        【讨论】:

          【解决方案4】:

          在关注 lo_fye 的列表时,我遇到了自定义装饰器的问题。 我没有设置默认的文件装饰器并得到以下异常:

          Warning: Exception caught by form: No file decorator found... unable to render file element Stack Trace:
          

          这个问题的答案是你的一个装饰器必须实现空接口 Zend_Form_Decorator_Marker_File_Interface

          【讨论】:

            【解决方案5】:

            在使用 ajax 请求时,有时也会发生错误。在没有 ajax 请求的情况下尝试一下,不要忘记多部分表单。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-01-15
              • 1970-01-01
              • 2015-08-06
              • 2013-05-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多