我正在使用Symfony4,FOSRestBundle和Symfony / Serializer构建REST API。
当我尝试提交表单时,收到验证错误“请上传文件”。
因此,我使用Controller
而非FOSRestController
创建了另一种表单。另外,我已将$form->submit($request->request->all())
替换为$form->handleRequest($request)
。而且有效!
因此,我认为问题出在$form->submit($request->request->all())
。
如何使用Symfony4和FOSRESTBundle通过API上传文件?
应用程序\实体\用户:
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User
{
// ...
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank(message="Please, upload the file.")
* @Assert\File(maxSize="50000k", mimeTypes={ "application/pdf", "application/vnd.ms-powerpoint" })
*/
private $file;
public function getFile()
{
return $this->file;
}
public function setFile($file): self
{
$this->file = $file;
return $this;
}
// ...
}
App \ Form \ UserType
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', FileType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => false
]);
}
}
App \ Controller \ UserController
class UserController extends FOSRestController
{
public function postUserAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$data = json_decode($request->request->all(), true);
$form->submit($data);
if ($form->isSubmitted() && $form->isValid()) {
$file = $user->getFile();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
$file->move(
$this->getParameter('file_directory'),
$fileName
);
$user->setFile($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->handleView($this->view(['status' => 'created'], Response::HTTP_CREATED, ['Access-Control-Allow-Origin' => '*']));
}
return $this->handleView($this->view($form->getErrors(true, false)));
}
}