I want to upload file with yii, I kinda did it. When I hit the submit button the file is saved in the folder where it should be. However, I want to add the filename to the database as well. How can I achieve this?
this is my controller :
public function actionUpload()
{
$model = new TourImage();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, ‘imageFile’);
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render(‘upload’, [
‘model’ => $model
]);
}
You can extract the name of the original file from UploadedFile.getInstance() and assign it to the attribute of your model (This is normally done in your model "TourImage", in the upload method that you have had to implement).
Therefore if you have this in your controller action:
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
Then, in the upload() method of your TourImage model:
$this->your_model_attribute = $this->imageFile->name; // The original name of the file being uploaded
Change your_model_attributes to the attribute of your model where you want to save the file name.
Look at the public properties of the UploadedFile object: https://www.yiiframework.com/doc/api/2.0/yii-web-uploadedfile