Symfony2 / File Upload - 如果文件字段为空,则guessExtension为null

时间:2015-08-23 18:55:56

标签: php symfony upload

我有文件字段,其中required = false,multiple = multiple。一切正常,但如果文件输入为空,symfony2会显示此错误。

Error: Call to a member function guessExtension() on null

这是我的表单类型:

->add('file', 'file', array(
                'multiple' => 'multiple',
                'data_class' => null,
                'required' => false,
                'mapped' => false,
                'attr' => array(
                    'maxSize' => '1024k',
                    'accept' => 'image/*',
                )
            ))

上传功能:

private function uploadImg($files)
    {
        $path = array();
        foreach ($files as $file) {
            $extension = $file->guessExtension();
            if (!$extension) {
                $extension = 'bin';
            }
            $randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
            $file->move('uploads/images/', $randomName);
            $path[] = $randomName;
        }
        return $path;
    }

如何检查文件输入是否为空?

$form['file']->getData();每次都会返回Array

2 个答案:

答案 0 :(得分:1)

您可以使用continue跳过空文件

    foreach ($files as $file) {
        if(!$file) {
            continue; //skip
        }

        $extension = $file->guessExtension();
        if (!$extension) {
            $extension = 'bin';
        }
        $randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
        $file->move('uploads/images/', $randomName);
        $path[] = $randomName;
    }

答案 1 :(得分:0)

对于Symfony 3,我使用了这种方法并且工作正常。

use Symfony\Component\HttpFoundation\File\UploadedFile;

public function updateAction(...){
  // $image is Entity property, change accordingly.
  $file = $item->getImage();
  if ($file instanceof UploadedFile) {
     ... upload code
  }
}