Uploading image file through API using Symfony2 & FOSRESTBundle

后端 未结 4 1946
梦毁少年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:21

    This is a full upload from api code bit. This does upload the file, but I am still having trouble with validating the uploaded file. Hope this helps.

    This uses fosrest bundle for REST.

    private function addResource(Entity $resource) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($resource);
        $em->flush();
    }
    
    private function processForm(Entity $resource)
    {
        $em = $this->getDoctrine()->getManager();
        $uploadedFile = null;
    
        $form = $this->createForm(new EntityForm(), $resource);
    
        foreach ($_FILES as $file) {
            $uploadedFile = new UploadedFile(
                $file['tmp_name'], 
                $file['name'], $file['type'],
                $file['size'], $file['error'], 
                $test = false);
        }
    
        $submitData = array(
            "file" => $uploadedFile,
        );
    
        $form->submit($submitData);
    
        if ($form->isValid()) {
            $repository = $this->getDoctrine()
                ->getRepository('AcmeBundle:Product');
    
            $view = View::create();
            $resource->setFile($uploadedFile);
    
            // handling api requests
            if ($this->getRequest()->getMethod() == "POST") {
    
                $this->addResource($resource);
    
                // store image url
                $resource = $repository->find($resource->getId());
    
                if ($resource->getImage()) {
                    $fs = new Filesystem();
    
                    if ($fs->exists($resource->getWebPath())) {
                        $resource->setImagePath($resource->getWebPath());    
                    }
    
                    $this->addResource($resource);
                }
    
                $view->setData($resource);
            } 
    
            return $view;
        }
    
        return View::create($form);        
    }
    

提交回复
热议问题