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

Catch and upload files from POST call

我在 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�b�C���%r�4S�&�5c
Ds��'ET�d6U���  ��L!1AQaq"��2����#��BR�br����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

如何捕捉 POST 文件并创建一个文件以通过 Symfony 上传到服务器?可以给我一些想法或示例代码吗?

编辑 1:

由于我使用的是 FOSRestBundleNelmioApiDocBundle,所以我使用的是 Nelmio 沙盒模式,如下图所示:

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

$re = "/(?P<headers>.*)[\r\n][\r\n](?P<content>.*)/mis";

preg_match_all ( $re, $request->getContent(), $matches );

print_r( $matches );

您应该能够从 $matches 中获取匹配的元素并使用 file_put_contents 或等价物。

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