How to upload a file to the server through the POST API in Yii2.0?

I am making a model in yii2 from this link http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html I send the file using the POST request in the API and get all the file information in my controller, but I can’t download the file using this Yii2.0 model created using the above link. The normal PHP file upload code works fine. Here is my controller code

public function actionUploadFile() { $upload = new UploadForm(); var_dump($_FILES); $upload->imageFile = $_FILES['image']['tmp_name']; //$upload->imageFile = $_FILES; var_dump($upload->upload()); } 

and my model code

 class UploadForm extends Model { /** * @var UploadedFile */ public $imageFile; public function rules() { return [ [['imageFile'], 'safe'], [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'], ]; } public function upload() { try { if ($this->validate()) { $this->imageFile->saveAs('/var/www/html/' . $this->imageFile->baseName . '.' . $this->imageFile->extension); var_dump("Jeree"); return true; } else { var_dump($this->getErrors()); return false; } }catch (ErrorException $e) { var_dump($e->getMessage()); } } } 
+5
source share
1 answer

Try this way

 public function actionUpload() { $model = new UploadForm(); if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, 'file'); if ($model->validate()) { $model->file->saveAs('/var/www/html/' . $model->file->baseName . '.' . $model->file->extension); } } return $this->render('upload', ['model' => $model]); } 
+3
source

Source: https://habr.com/ru/post/1233682/


All Articles