我正在尝试通过axios / ajax上传文件。 我这样上传文件:
const formData = new FormData();
formData.append('logoFile', e.files[0]);
axios.post('/startups/logo', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
然后在Symfony 4上,我要充水我的实体并验证使用formType创建的表单:
我的formType:
class LogoType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Remember username is email
$builder
->add('logoFile', VichFileType::class, [
'label' => false,
'required' => false,
'allow_delete' => false,
'download_uri' => true,
'download_label' => true,
'download_link' => true,
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_protection' => false,
));
}
}
但是在我的控制器中,我永远无法验证表单:
public function updateLogo(Request $request): Response
{
$image = $request->files->get('logoFile');
if(!$image instanceof UploadedFile) {
throw new HttpException(400, "Cannot find a file to upload. Try again.");
}
//$image is now an instance of Symfony\Component\HttpFoundation\File\UploadedFile
// THIS WORKS ^^ dd($image) does show the file properly
$logo = new Logo();
$form = $this->createForm(LogoType::class, $logo);
$form->submit($request->files->all());
if ($form->isSubmitted() && $form->isValid()) {
// THIS PART NEVER GETS HIT.
}
请注意,尝试执行$form->handleRequest($request);
无效,$form->submit($request->request->all());
也无效,这通常是验证通过ajax提交的表单的方法。
有人知道如何验证具有包含multipart / form-data文件集的表单吗?
谢谢大家。