Yii2 Display image stored in BLOB database field

守給你的承諾、 提交于 2019-12-04 17:47:47

Here is the official documentation on Yii2 https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md It is quite simple.

some comments:
1) the pics might be private and it might be a big problem if somebody guesses the path of others. In this case you can put the file someplace NOT in the web folder. If you do this then you have to use the assets to show them assetManager->getPublishedUrl('@app/folder')?>/fav.ico
2) if the pics are not so sensitive then you can just save them someplace in the web folder.

As you can see you might have problems with uploading the same file name 2 times, as 1 will override the other. You can always rename the file, I would actually change their code to something like this

        if ($model->file && $model->validate()) {
$model->file = UploadedFile::getInstance($model, 'file');
            $filePath = 'uploads/' . hash('ripemd160', microtime()) . $model->file->baseName . '.' . $model->file->extension;
            $model->fileName = $filePath;
            $model->save();

            $model->file->saveAs('uploadsimg/' . $model->file->baseName . '.' . $model->file->extension);
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(Url::toRoute(['create']));
            }
        }

The shortest way I found to display a image from a BLOB field (in a MySQL database) was using this code (in my view):

$sql = "SELECT FieldName FROM TableName"; //optional where statements etc.
$connection = Yii::$app->getDb();
$command = $connection->createCommand($sql);
$imgLogo = $command->queryScalar();
echo '<img src="data:image/jpeg;base64,'.base64_encode($imgLogo).'"/>';

Note that in this example I have only one row in the table 'TableName' as this example was used to retrieve the logo from the company. And there is only one company stored in that table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!