Uploading image file through API using Symfony2 & FOSRESTBundle

后端 未结 4 1939
梦毁少年i
梦毁少年i 2020-12-28 08:54

I have been coding an API for a photo sharing app like Instagram using Symfony2, FOSRESTBundle, and Vichuploader for file uploads.

I\'m able to work around GET and P

4条回答
  •  爱一瞬间的悲伤
    2020-12-28 09:06

    An example for a upload method exepting post requests:

    public function uploadAction() {
        $em = $this->getDoctrine()->getManager();
    
        $document = new Document();
    
        foreach ($_FILES as $file) {
    
            $document->setTitle($file['name']);
            $document->file = new UploadedFile($file['tmp_name'], 
                              $file['name'], $file['type'],
                              $file['size'], $file['error'], $test = false);
    
            $em->persist($document);
            $em->flush();
    
            break;
        }
    
        $serializer = $this->get('jms_serializer');
        $data = $serializer->serialize(
              $document, 'json', 
              SerializationContext::create()->setGroups(array('someGroup')));
    
        return new Response($data);
    }
    

    So this action first stores the document on the server and returns a json response containing document meta data and path. I used the response for further processing in my web application.

    I am not familiar with VichUploader, the above code is native Symfony2 code using Symfony\Component\HttpFoundation\File\UploadedFile.

    Read: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

提交回复
热议问题