/** * * @return type * @throws BadRequestHttpException */ public function run() { if (Yii::$app->request->isPost) { if (!empty($this->getParamName) && Yii::$app->getRequest()->get($this->getParamName)) { $this->paramName = Yii::$app->getRequest()->get($this->getParamName); } $file = UploadedFile::getInstanceByName($this->paramName); $model = new DynamicModel(compact('file')); $model->addRule('file', $this->_validator, $this->validatorOptions); if ($model->validate()) { if ($this->unique === true) { $model->file->name = uniqid() . (empty($model->file->extension) ? '' : '.' . $model->file->extension); } $result = $model->file->saveAs($this->path . $model->file->name) ? ['key' => $model->file->name, 'caption' => $model->file->name, 'name' => $model->file->name] : ['error' => 'Can\'t upload file']; } else { $result = ['error' => $model->getErrors()]; } if (Yii::$app->getRequest()->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; } return $result; } else { throw new BadRequestHttpException('Only POST is allowed'); } }
public function actionUploadAvatar() { if (Yii::$app->user->isGuest) { throw new NotFoundHttpException(Yii::t('yii', 'Page not found.')); } Yii::$app->response->format = Response::FORMAT_JSON; $model = new DynamicModel(['image']); $model->addRule('image', 'file', ['skipOnEmpty' => false, 'extensions' => 'png, jpg']); if (Yii::$app->request->isPost) { $model->image = UploadedFile::getInstanceByName('image'); if ($model->validate()) { try { return AvatarHelper::saveAvatar($model->image); } catch (Exception $exc) { Yii::$app->response->statusCode = 400; return Yii::t('yee', 'An unknown error occurred.'); } } else { $errors = $model->getErrors(); Yii::$app->response->statusCode = 400; return $model->getFirstError(key($errors)); } } return; }