Hakim
Hakim

Reputation: 1102

Symfony2 posting a file through REST API

I'm building a REST api using Symfony2, FOSRestBundle and JMSSerializerBundle. I have an URL that I use to change a user's avatar.

/api/users/{id}/avatar.json

I want to send an image to that URL to modify the avatar, but I get this error

"The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is  a(n) string

Here is my form type

class ChangeAvatarFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('picture', 'file')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User',
            'csrf_protection' => false,
        ));
    }

    // BC for SF < 2.7
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $this->configureOptions($resolver);
    }

    public function getName()
    {
        return 'api_user_change_avatar';
    }
}

Here is my controller

    /**
     * @Rest\Put("/{id}/avatar", requirements={"id" = "\d+"})
     * @Security("has_role('ROLE_CONTRIBUTOR')")
     * @Rest\View
     */
    public function putUserAvatarAction(Request $request, $id)
    {
        $userManager = $this->get('fos_user.user_manager');
        $user = $userManager->findUserBy(array('id' => $id));

        $form = $this->createForm(new ChangeAvatarFormType(), $user, array('method' => 'PUT'));
        $form->handleRequest($request);

        if ($form->isValid()) {

            $userManager->updateUser($user);

            return new Response('', 204);
        } else {
            return $this->view($form, 400);
        }
    }

And here is my POSTMAN configuration: enter image description here

I have tried using a POST method too, instead of PUT. The file is sent to the server, it appears when I var_dump $_FILES I don't understand why the binding is not working as expected.

Upvotes: 2

Views: 2114

Answers (1)

Geoffroy
Geoffroy

Reputation: 146

Isn't your $user->getPicture() returning a string?
At form creation when you pass data, it will try to set the defaults but the FileType form field only accepts a File object.

Upvotes: 2

Related Questions