Add filename to db

Hey all,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. Hovewer, 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
]);

}`

Hi!

You could try like this:

if(!$model->imageFile->hasError) {
$file = $model->imageFile;
$model->blob_file_content = chunk_split(base64_encode(file_get_contents($file->tempName)));
$model->file_extension = pathinfo($file->name, PATHINFO_EXTENSION); // or save the original name ?
$model->file_mimetype = mime_content_type($file->name);
}

To read the file and output:

$filename = 'name_of_file.' . $model->file_extension; // or read the original filename
$content  = base64_decode($model->blob_file_content);

return \Yii::$app->response->sendContentAsFile($content, $filename, ['mimeType' => $model->file_mimetype]);

Here’s an example of storing image filename in db.
https://forum.yiiframework.com/t/the-tutorial-on-how-to-upload-an-image-to-yii2-model/123464

1 Like