从 NextJS 中的 API 响应渲染图像 - 只需下载 base64 文件

Boa*_*rdy 4 api base64 image next.js

我正在开发一个新项目并学习 ReactJS。我已将 Base64 格式的图像保存到 MySQL 数据库,现在尝试执行 GET 请求,以便图像显示在浏览器中而不是被下载,但是,尽管它尝试下载该文件,但该文件只是一个包含 base64 字符串而不是实际图像的文件。

数据库中的文件如下所示(仅是base64的片段)

data:image/png;base64,iVBORw0KGgoAAAA
Run Code Online (Sandbox Code Playgroud)

获取图片的API如下:

export default async function handler(req : NextApiRequest, res : NextApiResponse) {
    const prisma = new PrismaClient()

    if (req.method === "GET")
    {
        const {image_id} = req.query;
        const image = await prisma.images.findFirst({
            where: {
                imageId: parseInt(image_id)
            }
        });
        const decoded = Buffer.from(image.content).toString("base64");
        console.log(decoded)
        res.status(200).send(decoded);
    }
    else
    {
        res.status(405).json(returnAPIErrorObject(405, "Method not supported by API endpoint"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我修改了 next.config.js 以提供自定义标头响应,其中包含以下内容:

module.exports = {
    async headers() {
        return [
            {
                source: '/api/images/:image_id',
                headers: [
                    {
                        key: 'Content-Type',
                        value: 'image/png:Base64'
                    }
                ]
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

如前所述,当我访问 URL http://localhost:3000/api/images/4(4 是图像 ID)时,它会下载一个包含数据库中的 base64 字符串的文件,而不是在浏览器中显示图像。

更新

根据@sean 评论中的链接,它现在尝试显示图像,但不是显示实际图片,而是仅显示一个带有白色方块的空白窗口,如下面的屏幕截图所示。

我的代码现在如下所示:

        const {image_id} = req.query;
        const image = await prisma.images.findFirst({
            where: {
                imageId: parseInt(image_id)
            }
        });

        const decoded = Buffer.from(image.content, 'base64').toString();

        let imageContent = decoded.replace(/^data:image\/png;base64,/, '');

        console.log(decoded);

        res.writeHead(200, {
            'Content-Type': 'image/png',
            'Content-Length': imageContent.length
        });
        res.end(imageContent);
Run Code Online (Sandbox Code Playgroud)

下面的屏幕截图显示了页面上实际呈现的内容,而不是我的实际图像。

如何显示图像而不是实际图像

Boa*_*rdy 5

我已经解决了这个问题,而不是从数据库创建缓冲区,我认为看起来像 Prisma,因为该列是一个 blob,无论如何都给了我一个缓冲区。,我首先从数据库中提取 base64 字符串,并从字符串中删除 data:image/png;base64,然后从该字符串创建一个缓冲区并将其发送给响应:

const {image_id} = req.query;
        const image = await prisma.images.findFirst({
            where: {
                imageId: parseInt(image_id)
            }
        });

        const decoded = image.content.toString().replace("data:image/png;base64,", "");
        const imageResp = new Buffer(decoded, "base64");

        res.writeHead(200, {
            'Content-Type': 'image/png',
            'Content-Length': imageResp.length
        });
        res.end(imageResp);
Run Code Online (Sandbox Code Playgroud)