You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8向PostgreSQL存PNG二维码报UTF8 0x89无效字节序列解决方案

问题描述

Windows 10系统下使用Laravel 8开发,需求为将生成的二维码存入PostgreSQL数据库。该功能在本地MySQL环境运行正常,部署到Heroku远程主机时抛出如下错误:

SQLSTATE[22021]: Character not in repertoire: 7 ERROR:  invalid byte sequence for encoding "UTF8": 0x89

曾尝试将config\database.php中远程数据库的编码修改为和本地一致的utf8mb4,问题未得到解决。

相关代码片段

二维码生成与存储代码(database\seeders\DatabaseSeeder.php)

use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Models\QrCodeClient;

$client1qr = QrCode::format('png')->encoding('utf8')->size(100)->generate($client1->id);

QrCodeClient::create([
    'client_id' => $client1->id,
    'qrcode' => $client1qr,
]);

备注:最初代码未添加->encoding('utf8')参数,同样抛出相同错误。

QrCodeClient模型对应迁移文件代码

Schema::create('qr_code_clients', function (Blueprint $table) {
    $table->id();
    $table->foreignId('client_id');
    $table->binary('qrcode');
    $table->index('client_id');
    $table->timestamps();
});

PostgreSQL数据库配置

'pgsql' => [
    'driver' => 'pgsql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '5432'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
    'prefix_indexes' => true,
    'schema' => 'public',
    'sslmode' => 'prefer',
],
解决方案

对生成的二维码内容做base64编码后再写入数据库,存储代码调整如下:

$client1qr = QrCode::format('png')->generate($client1->id);
$escaped1 = base64_encode($client1qr);

QrCodeClient::create([
   'client_id' => $client1->id,
   'qrcode' => $escaped1,
]);

前端展示代码如下:

<?php
$my_bytea = stream_get_contents($bed->client()->first()->QrCode()->first()->qrcode);
$my_string = pg_unescape_bytea($my_bytea);
$html_data = htmlspecialchars($my_string);
?>
<td><img src="data:image/png;base64,{{$html_data}}"></td>

内容的提问来源于stack exchange,提问作者birbhouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 11:54:01