2015-05-29 30 views
1

我正在爲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?有什麼建議?

+0

你缺少'$ uploadedFile'參數或設置變量。 –

+0

@LordZed我編輯了我的答案,我已經定義了'$ uploadedFile' – ReynierPM

回答

2

$request->filesFileBag的實例。使用$request->files->get('keyoffileinrequest')獲取文件。

rid被指定是一個必需的參數,所以是的,它會拋出一個BadRequestHttpException如果你沒有設置它。它表現得應該如此。您應該嘗試將rid設置爲不在數據庫中的ID,然後您應該看到自己的錯誤消息。

如果你想rid是可選的,你可以爲rid添加一個默認值:

* @RequestParam(name="rid", nullable=false, requirements="\d+", default=0, description="The ID of the representative") 

類似的東西。現在rid將爲零,您的Repository :: find調用可能會返回null,並返回錯誤視圖。但我建議你保持它的樣子,這是正確的行爲。

相關問題