我正在尝试在SF3中上传图像,并且在上传时出现此错误:
Symfony \ Component \ HttpFoundation \ File \ UploadedFile :: __ construct()缺少参数2。
这是错误所在的我实体的一部分(此处是第9行):
public function preUpload()
{
// if there is no file (optional field)
if (null === $this->image) {
return;
}
// $file = new File($this->getUploadRootDir() . '/' . $this->image);
$file = new File($this->getUploadRootDir() .'/' . $this->image);
$uploadedfile = new UploadedFile($this->getUploadRootDir() .'/' . $this->image);
// the name of the file is its id, one should just store also its extension
// to make clean, we should rename this attribute to "extension" rather than "url"
$this->url = $file->guessExtension();
// and we generate the alt attribute of the <img> tag,
// the value of the file name on the user's PC
$this->alt = $uploadedfile->getClientOriginalName();
}
然后是我的控制器:
public function mediaEditAction(Request $request)
{
$media = new Media();
$form = $this->createForm(MediaType::class, $media);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $media->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move(
$this->getParameter('images_directory'),
$fileName
);
$media->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
$request->getSession()->getFlashBag()->add('Notice', 'Photo added with success');
// redirection
$url = $this->generateUrl('medecin_parametre');
// permanent redirection with the status http 301
return $this->redirect($url, 301);
} else {
return $this->render('DoctixMedecinBundle:Medecin:mediaedit.html.twig', array(
'form' => $form->createView()
));
}
}
答案 0 :(得分:0)
似乎您正在做不必要的工作,并使此工作比可能需要的复杂一些。您遵循了这个Symfony guide for How to Upload Files吗?
与此同时,图像名称似乎是$this->image
中的名称,因此您可以将其作为第二个构造函数参数传递。
$uploadedfile = new UploadedFile($this->getUploadRootDir().'/'.$this->image, $this->image);
但是, UploadedFile 可能应该仅来自表单提交,并且在您的实体中,您想使用 File -像这样:
use Symfony\Component\HttpFoundation\File\File;
$uploadedfile = new File($this->getUploadRootDir() .'/' . $this->image);