我正在爲RESTful API製作POST
方法。您可能會注意到,該API構建在FOSRestBundle和NelmioApiDoc之上。我無法驗證文件何時未上傳,或者何時rid
參數丟失,並且響應正確的JSON。這是我在做什麼:如何在FOSRestBundle的RESTful API中爲POST方法設置正確的JSON響應?
/**
* 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, 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();
$uploadedFile = $request->files;
// this is not working I never get that error if I not upload any file
if (empty($uploadedFile)) {
$view->setData(array('error' => 'invalid or missing parameter'))->setStatusCode(400);
return $view;
}
$em = $this->getDoctrine()->getManager();
$entReps = $em->getRepository('PDOneBundle:Representative')->find($paramFetcher->get('rid'));
if (!$entReps) {
$view->setData(array('error' => 'object not found'))->setStatusCode(400);
return $view;
}
.... some code
$repsData = [];
$view->setData($repsData)->setStatusCode(200);
return $view;
}
如果我沒有上傳文件,我得到這個迴應:
Error: Call to a member function move() on a non-object
500 Internal Server Error - FatalErrorException
但是symfony異常錯誤不是作爲一個JSON,因爲我想要和需要的,所以代碼從未輸入if
。
如果我沒有設置rid
然後我得到這個錯誤:
Request parameter "rid" is empty
400 Bad Request - BadRequestHttpException
但同樣作爲Symfony的異常錯誤,而不是一個JSON。如果rid
不存在或文件沒有上傳,我該如何回覆正確的JSON?有什麼建議?
你缺少'$ uploadedFile'參數或設置變量。 –
@LordZed我編輯了我的答案,我已經定義了'$ uploadedFile' – ReynierPM