image - Symfony 3 中的 ContextErrorException
问题描述
我正在尝试在 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()
));
}
}
解决方案
似乎您正在做不必要的工作,并使这比它可能需要的复杂一点。您是否遵循了如何上传文件的 Symfony 指南?
同时,看起来图像名称就是其中的内容,$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);