0

我想确保在文件上传期间,只允许使用 jpeg、png 和 gif 格式的文件。所以截图下面的“文件类型:”必须显示jpeg、png和gif:

http://lh5.ggpht.com/_SDci0Pf3tzU/ScynOZt_0qI/AAAAAAAAEo0/gMr_zxYofV4/s400/styleerror.png

我在 Symfony 中为我的验证器做了以下操作:

$this->setValidator ( 'upload your filehere',
     new sfValidatorFile ( array (
     'required'=>true,
     'mime_types' => array ('image/jpeg, image/png, image/gif' )
      ) ,
      array(

      'mime_types'=> 'only jpeg'
      )
      ) 
      );

但是当我点击上传按钮时,文件没有被相应地过滤;我做错什么了?

我也试试

$this->setValidator ( 'upload your filehere',
     new sfValidatorFile ( array (
     'required'=>true,
     'mime_types' => 'image/jpeg, image/png, image/gif' 
      ) ,
      array(

      'mime_types'=> 'only jpeg'
      )
      ) 
      );

但它也不起作用。

我在我的表单类中尝试了以下方法,但不幸的是它不起作用:

<?php

class UploadCaseForm extends sfForm {
    public function configure() {
        $this->setWidgets ( array ('Documents' => new sfWidgetFormInputFile ( ) ) );
        $this->widgetSchema->setNameFormat ( 'UploadCase[%s]' );


        $this->validatorSchema ['Documents'] = new sfValidatorFile ( 
        array ('mime_types' => 'web_images' ), 
        array ('invalid' => 'Invalid file.',
         'required' => 'Select a file to upload.', 
         'mime_types' => 'The file must be of JPEG, PNG or GIF format.' ) );

    }
}
?>

这是操作代码:

    public function executeIndex(sfWebRequest $request) {
        $this->form = new UploadCaseForm ( );

if ($this->getRequest ()->getMethod () == sfRequest::POST) {
        var_dump($request->getParameter('UploadCase'));


    }

}

编辑:就服务器端验证而言,接受的答案就是答案。如果有人想要客户端验证,即在操作到达服务器之前过滤可以上传的文件类型,那么由于浏览器的限制,可能没有可靠的方法来做到这一点

4

2 回答 2

3

您似乎错误地使用了 API。sfForm::setValidator() 的签名在这里

然而,这里有一个简单的方法来设置一个文件验证器,它只允许上传网络图像:

$this->validatorSchema['my_file'] = new sfValidatorFile(array(
    'mime_types' => 'web_images'
), array(
    'invalid'    => 'Invalid file.',
    'required'   => 'Select a file to upload.',
    'mime_types' => 'The file must be of JPEG, PNG or GIF format.'
));

“web_images”类别包括以下 MIME 类型:

image/jpeg
image/pjpeg
image/png
image/x-png
image/gif

如果您想明确定义要接受的 MIME 类型,请将“web_images”替换为如下类型的数组:

'mime_types' => array(
    'image/jpeg',
    'image/pjpeg',
    'image/png',
    'image/x-png',
    'image/gif'
)
于 2009-03-27T09:02:52.753 回答
0

有一种方法可以限制在浏览器中上传文件的选择。
缺点是它使用 flash 来选择文件,并且限制了对安装了 flash 播放器的用户的支持。优点是 Flash 让您可以更好地控制上传(并行上传、进度、错误、允许选择的控制文件扩展名等)。

我为此使用的组件是swfupload

编辑:这并不能免除对上传文件进行服务器端控制,但结合使用它可以提供类似的安全级别和更好的用户体验(错误可能在长时间运行的上传开始之前发生)

于 2010-05-04T14:33:58.507 回答