This has been covered but I feel it’s not easy enough.
Here are the steps
-
Add Image upload to your Model
use yii\web\UploadedFile;
-
Add a new variable to hold the uploaded image.
public $eventImage;
-
Add a rule to handle this variable.
I prefer to add my image after I have created a row, this makes it easier should you have a failure to upload something.[['eventImage'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
-
Define logic in your Controller to save the file to a path of your choice
public function actionUpload($id)
{
$model = $this->findModel($id);if (Yii::$app->request->isPost) { $model->eventImage = UploadedFile::getInstance($model, 'eventImage'); if ($model->upload()) { return $this->redirect(['view', 'id' => $model->id]); } } return $this->render('upload', ['model' => $model]);
}
- Watch out for naming of variables issue. This is the biggest problem. $this->eventImage must be the variable pointing to it. if something does not work, its probably the naming.
-
Create a upload path function in the model. Use a seperate model function so that you can test it separately. Do not forget to create the folder for it
public function upload() { if (true) { $path = $this->uploadPath() . $this->id . "." .$this->eventImage->extension; $this->eventImage->saveAs($path); $this->image = $this->id . "." .$this->eventImage->extension; $this->save(); return true; } else { return false; }
}
public function uploadPath() { return Url::to('@web/uploads/events');
}