Answer the question
In order to leave comments, you need to log in
Symfony Form & FOSRESTBundle: How to upload a file?
I am developing a REST API using Symfony4, FOSRestBundle and Symfony/Serializer.
I send a POST request via Postman (file). Throws validation error 'Please, upload the file' (field file
empty) on submit.
I created another form using Controller instead of FOSRestBundle. That is, I displayed the html form on the page ( $this->render()
). Replaced $form->submit($request->request->all())
with $form->handleRequest($request)
, left the rest as is. The file is being loaded.
That is the case in handleRequest
? But how to use it with json?
App\Entity\User:
/**
* @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;
}
// ...
}
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
]);
}
}
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)));
}
}
Answer the question
In order to leave comments, you need to log in
You forgot to add data from files. You can see how it's done in HttpFoundationRequestHandler
$params = $request->request->all();
$files = $request->files->all();
$data = array_replace_recursive($params, $files);
$form->submit($data);
submit
as shown above. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question