API Post to Sonata Media Bundle Symfony 3

724 views Asked by At

My purpose is to send a picture from an Ionic App (For now testing with PostMan) to my Symfony 3 based database using Sonata Media Bundle.

Their is a documentation but it's quite short and I'm stuck to the 15.3. SENDING A MEDIA FILE process.

I managed to get the follow process in the Bundle and inspect data. c:\wamp64\www\bumblb___api\vendor\sonata-project\media-bundle\Controller\Api\MediaController.php > handleWriteMedium() function.

/**
 * Write a medium, this method is used by both POST and PUT action methods.
 *
 * @param Request                $request
 * @param MediaInterface         $media
 * @param MediaProviderInterface $provider
 *
 * @return View|FormInterface
 */
protected function handleWriteMedium(Request $request, MediaInterface $media, MediaProviderInterface $provider)
{
    $form = $this->formFactory->createNamed(null, 'sonata_media_api_form_media', $media, array(
        'provider_name' => $provider->getName(),
        'csrf_protection' => false,
    ));

    // return $media;
    // return $request->__toString();

    // THE FORM DOES NOT FILL WITH REQUEST
    $form->handleRequest($request);
    return $form->getData();
    // return $media;


    if ($form->isValid()) {

        $media = $form->getData();
        $this->mediaManager->save($media);

        $view = FOSRestView::create($media);

        // BC for FOSRestBundle < 2.0
        if (method_exists($view, 'setSerializationContext')) {
            $serializationContext = SerializationContext::create();
            $serializationContext->setGroups(array('sonata_api_read'));
            $serializationContext->enableMaxDepthChecks();
            $view->setSerializationContext($serializationContext);
        } else {
            $context = new Context();
            $context->setGroups(array('sonata_api_read'));
            $context->setMaxDepth(0);
            $view->setContext($context);
        }

        return $view;
    } else {
        // return "NOT VALID";
    }

    return $form;
}

Which is called be this one :

/**
 * Adds a medium of given provider
 * If you need to upload a file (depends on the provider) you will need to do so by sending content as a multipart/form-data HTTP Request
 * See documentation for more details.
 *
 * @ApiDoc(
 *  resource=true,
 *  input={"class"="sonata_media_api_form_media", "name"="", "groups"={"sonata_api_write"}},
 *  output={"class"="Sonata\MediaBundle\Model\Media", "groups"={"sonata_api_read"}},
 *  statusCodes={
 *      200="Returned when successful",
 *      400="Returned when an error has occurred while medium creation",
 *      404="Returned when unable to find medium"
 *  }
 * )
 *
 * @Route(requirements={"provider"="[A-Za-z0-9.]*"})
 *
 * @param string  $provider A media provider
 * @param Request $request  A Symfony request
 *
 * @return MediaInterface
 *
 * @throws NotFoundHttpException
 */
public function postProviderMediumAction($provider, Request $request)
{
    $medium = $this->mediaManager->create();
    $medium->setProviderName($provider);

    try {
        $mediaProvider = $this->mediaPool->getProvider($provider);
    } catch (\RuntimeException $ex) {
        throw new NotFoundHttpException($ex->getMessage(), $ex);
    } catch (\InvalidArgumentException $ex) {
        throw new NotFoundHttpException($ex->getMessage(), $ex);
    }

    return $this->handleWriteMedium($request, $medium, $mediaProvider);
}

I choose to make it using JSON with POSTMAN. Form-data does not seems to work.

http://127.0.0.1:8000/api/providers/sonata.media.provider.image/media

{
"name": "nameex",
"description": "descriptionex",
"copyright": "copyrightex",
"authorName": "authorNameex",
"cdnIsFlushable": true,
"enabled": true,
"binaryContent": "data:image/jpeg;base64,test"
}

the differents return that I write to test :

return $form->getData();

{
        "provider_metadata": [],
        "enabled": false,
        "provider_name": "sonata.media.provider.image"
    }

return $request->__toString();

"POST /api/providers/sonata.media.provider.image/media HTTP/1.1\r\nAccept:          */*\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4\r\nAuthorization:   Basic c3VwZXI6c3VwZXI=\r\nCache-Control:   no-cache\r\nConnection:      keep-alive\r\nContent-Length:  201\r\nContent-Type:    application/json\r\nHost:            127.0.0.1:8000\r\nOrigin:          chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop\r\nPhp-Auth-Pw:     super\r\nPhp-Auth-User:   super\r\nPostman-Token:   16103fb6-3847-efe8-9cc6-7aa2a48b4ff9\r\nUser-Agent:      Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36\r\nX-Php-Ob-Level:  1\r\n\r\n{\n\t\"name\": \"namee\",\n\t\"description\": \"description\",\n\t\"copyright\": \"copyright\",\n\t\"authorName\": \"authorName\",\n\t\"cdnIsFlushable\": true,\n\t\"enabled\": true,\n\t\"binaryContent\": \"data:image/jpeg;base64,patata\"\n}"

The request seems to be OK but the form is not being filled with it. I compare the request with another form post which is working, it's the same structure.

The form is never valid, because vield "should not be blank".

I will may find a solution testing form-data in another way.. Trying to send a real baseEncode image value..

I know it's a very specific case but if someone was in this case or was able to offer my a different point of view would be wonderfull. Or I will have to give up on Media Bundle which is perfectly working with the admin and reception just because of that :(

Thank you

1

There are 1 answers

0
Paul Leclerc On BEST ANSWER

The solution was just to do not override POSTMAN Headers Content-Type when using form-data type format.

Overriding POSTMAN Content-Type makes the POST being send empty..

After my tests in Postman, I used DATA_URL picture format to send it using Ionic and the MediaBundle API. (with Blob conversion and FormData javascript system)