从POST调用中捕获并上载文件

时间:2015-05-29 04:06:27

标签: php symfony symfony-2.6

我正在使用REST Api工作,我正在POST发送(上传)文件。我正在使用Symfony 2.6.8和FOSRestBundle,我这样做的方法是:

/**
 * 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;
}

这就是我得到的回应:

------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

如何通过Symfony捕获该POST文件并创建上传到服务器的文件?可以给我任何想法或示例代码吗?

EDIT1:

由于我正在使用FOSRestBundleNelmioApiDocBundle我正在使用Nelmio Sandbox模式,如下图所示:

enter image description here

1 个答案:

答案 0 :(得分:0)

我会使用正则表达式来打破你打印的内容:

Couldn't find Tech with 'id'=

您应该可以从:~/t> more test.txt A1 2 123 f f j j k k :~/t> awk '{for(i=j=4; i < NF; i+=2) {$j = $i$(i+1); j++} NF=j-1}1' test.txt A1 2 123 ff jj kk 获取匹配的元素并使用:~/t> more test.txt A1 2 123 f f j j k k A2 10 789 f o p f m n :~/t> awk '{for(i=j=4; i < NF; i+=2) {$j = $i$(i+1); j++} NF=j-1}1' test.txt A1 2 123 ff jj kk A2 10 789 fo pf mn 或同等的元素。

示例:https://regex101.com/r/oW6fM4/1