使用Yii2(php)从Postgresql数据库检索图像 [英] Retrieving image from postgresql database using Yii2 (php)
问题描述
我们在使用yii2从postgres数据库中检索上传的图像时遇到了问题
We have a problem retrieving uploaded image from postgres database with yii2
我们用这种方式将图像存储到db:
we store image with that way to the db:
$data = pg_escape_bytea(file_get_contents($model->CheckIfAvatarExists(Yii::$app->user->identity->username)));
$profile->passphoto = new Expression("'{$data}'");
$profile->save();
完美存储图像
但是当我们尝试显示图像,它不起作用:
but when we try to display image, it is not working:
header('Content-type: image/png');
echo pg_unescape_bytea( $profile->passphoto);
我认为最大的问题是数据转义后不会恢复原状
I think the big problem is data after escaped it wont back to original be unescape
有没有解决方案?
推荐答案
请在 pg_unescape_bytea 在线文档:
PostgreSQL 9.0引入了 hex作为编码
二进制数据的新默认格式。由于 pg_unescape_bytea仅适用于旧的
转义格式,因此您需要执行pg_query(’SET byteateaoutput =
转义;');在执行您选择的查询之前。
PostgreSQL 9.0 introduced "hex" as the new default format for encoding binary data. Because "pg_unescape_bytea" only works with the old "escape" format, you need to do pg_query('SET bytea_output = "escape";'); before executing your select queries.
事实上,只有当客户端库早于9.0 时,这才是正确的(我相信libq.so.5.2,现在已经停产了。)
In fact, it's only true when the client library is older than 9.0 (libq.so.5.2 I believe, now EOL'ed).
如果您的情况如此,那就说明了错误转义的问题。
If that is your case, that explains the problem of wrong unescaping.
要强制 bytea_output
到 escape
正确解码,可以选择:
To force bytea_output
to escape
to decode properly, you may either :
- 动态地使用
SET bytea_output = escape;
作为会话中的SQL命令 - 或整个数据库的静态:
ALTER DATABASE SET bytea_output = escape;
- 或
postgresql.conf
用于整个实例。
- dynamically with
SET bytea_output=escape;
as a SQL command in the session - or statically for the whole database:
ALTER DATABASE SET bytea_output=escape;
- or in
postgresql.conf
for the whole instance.
理想的解决方案是升级将 libpq
客户端库升级到较新的版本,在这种情况下,没有必要这样做,它就可以使用。
The ideal solution would be to upgrade the libpq
client library to a newer version, in which case none of this is necessary, it just works.
这篇关于使用Yii2(php)从Postgresql数据库检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!