我有文件字段,其中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
答案 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
}
}