I am working in a REST Api and I am sending (uploading) a file in a POST
. I am working with Symfony 2.6.8 and FOSRestBundle and I am doing this is on the method:
/**
* Set and upload avatar for reps.
*
* @param ParamFetcher $paramFetcher
* @param Request $request
*
* @ApiDoc(
* resource = true,
* https = true,
* description = "Set and upload avatar for reps.",
* statusCodes = {
* 200 = "Returned when successful",
* 400 = "Returned when errors"
* }
* )
*
* @RequestParam(name="rid", nullable=false, strict=true, requirements="\d+", description="The ID of the representative")
* @RequestParam(name="avatar", nullable=false, description="The avatar file")
*
* @return View
*/
public function postRepsAvatarAction(ParamFetcher $paramFetcher, Request $request)
{
$view = View::create();
$content = $request->getContent();
print_r($content);
$view->setData(array())->setStatusCode(200);
return $view;
}
And this is what I am getting as response:
------WebKitFormBoundary3JCHTJWwvnOcvnSv
Content-Disposition: form-data; name="_format"
json
------WebKitFormBoundary3JCHTJWwvnOcvnSv
Content-Disposition: form-data; name="rid"
1
------WebKitFormBoundary3JCHTJWwvnOcvnSv
Content-Disposition: form-data; name="avatar"; filename="carlingford.jpg"
Content-Type: image/jpeg
/* Here goes a lot of code that I suppose is image or so in base64 - below is just a example*/
���p��
��T!1"AQa2q�#B�� R�$3b�C���%r�4S�&�5c
Ds��'ET�d6U��� ��L!1AQaq"��2����#��BR�b$3r����C%4S��s�&5DTc���?�g������F΅%v9��Ge�9�С@#B�'�y�4!p|hPW%<�8�:n��9�hI�B;�Ж�:R{�8Ћ(�m�:m�*����0��vƄ#��?'B���BQ����BGo}
;#�a#�΄U��W�x?�E��H��:��#Ռ�t�L�6C�u ��#�R����22����n�c���B�@3ƅ"��ZRN�dv΄�����Д��pB��'B]�rҥ�����Q���)P�� �R�����R9Y�I&��� =���X?�bI�u��ĮQ���!C�'dn�}��-n�s�j8 �c$����Q����$�q��� �@�J9$ryԁj�pN�9���B8+*��v�Sih�J}[�W��ґ���R�r�?��h�I�J!�P�?J��+��T���+��Q�)�m
od
How do I catch that POST file and create a file for upload to server through Symfony? Can any give me ideas or sample code?
EDIT1:
Since I am using FOSRestBundle
and NelmioApiDocBundle
I am using Nelmio Sandbox mode as shown in the image below:
I would use regex to break out what you have printed:
$re = "/(?P<headers>.*)[\\r\\n][\\r\\n](?P<content>.*)/mis";
preg_match_all ( $re, $request->getContent(), $matches );
print_r( $matches );
You should be able to take the matched element from $matches
and use file_put_contents
or equivalent.
Example: https://regex101.com/r/oW6fM4/1