如何使用从API上传的Yii2 getInstancesByName验证文件?

时间:2018-10-02 11:26:04

标签: api validation yii2 image-uploading

我正在开发一个移动应用程序,Yii2用作后端API,问题是我无法验证上传的文件,我知道该怎么做?

    public static function uploadPicture ($vid) {
  $model = new Pictures ();
  $model->load(\Yii::$app->getRequest()->getBodyParams(), '');
  $model->vid_image = \yii\web\UploadedFile::getInstancesByName('vid_image');
  $imageDir = Yii::$app->params[ 'uploadDir' ];


  //if ( $model->validate() AND !empty($model->vid_image) ) { //does not work
  if ( !empty($model->vid_image) ) {
    foreach ( $model->vid_image as $images => $image) {
      $model->name = "t_" . time() . "_i_" . uniqid() . '.' . $image->extension;
      $model->vid = $vid;


      echo $image->hasError;//return empty
      //Yii::$app->end();
      //if ( $model->save() and $model->validate() ) { // does not work
      if(1==1 and $model->validate()){ // $model->validate() always empty!!!
        $image->saveAs($imageDir . '/' . $model->name);
        Yii::$app->getResponse()->setStatusCode(201);
        $id = implode(',', array_values($model->getPrimaryKey(true)));
        Yii::info("[pic.21] image: " . $model->name . " uploaded to: " . $imageDir, __METHOD__);
      } elseif ( $model->hasErrors() ) {
        $response = \Yii::$app->getResponse();
        $response->setStatusCode(500);
        throw new ServerErrorHttpException('Failed to create the object for unknown reason. [APIx001]');
      }
    }
  }
  return $model;
}

文件上传时未经验证。

谢谢

0 个答案:

没有答案