我目前收到以下错误:
"表单的视图数据应该是Symfony \ Component \ HttpFoundation \ File \ File类的实例,但是是(n)字符串。您可以通过设置" data_class"来避免此错误。 null的选项或添加视图转换器,将(n)字符串转换为Symfony \ Component \ HttpFoundation \ File \ File的实例。"
SoundController - 上传功能
/**
* @Security("is_granted('IS_AUTHENTICATED_FULLY')")
* @Route("/song/upload", name="upload_song")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function uploadSong(Request $request)
{
$song = new Sound();
$form = $this->createForm(SoundType::class, $song);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$file = $song->getFile();
$user = $this->getUser();
$fileName = $this
->get('app.file_uploader')
->setDir($this->get('kernel')->getRootDir()."/../web".$this->getParameter('songs_directory'))
->upload($file);
$song->setFile($fileName);
$file = $song->getCoverFile();
if ($file === null)
{
$song->setCoverFile($this->getParameter('default_cover'));
}
else
{
$fileName = $this
->get('app.file_uploader')
->setDir($this->get('kernel')->getRootDir()."/../web".$this->getParameter('covers_directory'))
->upload($file);
$song->setCoverFile($fileName);
}
$song->setUploader($user);
$song->setUploaderID($user->getId());
$user->addSong($song);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($song);
$entityManager->flush();
return $this->redirectToRoute('song_view', [
'id' => $song->getId()
]);
}
return $this->render('song/upload.html.twig', [
'form' => $form->createView()
]);
}
SoundType - 表格
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class)
->add('coverFile', FileType::class, [
'required' => false
])
->add('songName', TextType::class)
->add('songAuthor', TextType::class);
}
答案 0 :(得分:12)
以下是答案:
{
$builder
->add('file', FileType::class, array('data_class' => null))
->add('coverFile', FileType::class, array('data_class' => null))
->add('coverFile', FileType::class, array('data_class' => null,'required' => false))
->add('songName', TextType::class)
->add('songAuthor', TextType::class);
}
答案 1 :(得分:3)
/**
* @ORM\Column(type="string")
*
* @Assert\NotBlank(message="Please, upload the song as a MP3 file.")
* @Assert\File(mimeTypes={ "audio/mpeg", "audio/wav", "audio/x-wav", "application/octet-stream" })
*/
private $file;
您告诉学说您要存储字符串,但是您在表单中呈现一个上传按钮,该按钮会向您发送一个您根本不想存储在数据库中的物理文件。相反,您希望将文件从临时目录移动到上传目录,并且您想要记住数据库中的文件名称,因此您需要此属性为字符串。
最好的方法是遵循此page