简体   繁体   English

Symfony2通过REST API发布文件

[英]Symfony2 posting a file through REST API

I'm building a REST api using Symfony2, FOSRestBundle and JMSSerializerBundle. 我正在使用Symfony2,FOSRestBundle和JMSSerializerBundle构建REST api。 I have an URL that I use to change a user's avatar. 我有一个用于更改用户头像的URL。

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

I want to send an image to that URL to modify the avatar, but I get this error 我想向该URL发送图像以修改头像,但是出现此错误

"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: 这是我的POSTMAN配置: 在此处输入图片说明

I have tried using a POST method too, instead of PUT. 我也尝试过使用POST方法,而不是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. 该文件被发送到服务器,当我var_dump $_FILES我不明白为什么绑定不能按预期工作时,它就会出现。

Isn't your $user->getPicture() returning a string? 您的$ user-> getPicture()是否返回字符串?
At form creation when you pass data, it will try to set the defaults but the FileType form field only accepts a File object. 在创建表单时,当您传递数据时,它将尝试设置默认值,但FileType表单字段仅接受File对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM