将blob文件从MySQL数据库转换为图像在NextJS应用程序中存在困难。

huangapple go评论62阅读模式
英文:

Having trouble translating blob file into image on NextJS App from MySQL Database

问题

我正在处理一个项目,试图从数据库中提取一个存储为Blob文件的图像,但是图像无法显示。

第一个文件中的代码,products.jsx:

import React from "react";
import Image from 'next/image';
import { useEffect, useState } from "react";
import { StylesContext } from "@material-ui/styles";

export default function Home() {
    const[dataResponse, setdataResponse] = useState([]);
    useEffect(() => {
        async function getPageData() {
            const apiUrlEndpoint = 'http://localhost:3000/api/getdata';

            const response = await fetch(apiUrlEndpoint);
            const res = await response.json();
            console.log(res.products);
            setdataResponse(res.products)
        }
        getPageData();
    }, []);

    return (
        
        <div className='bg-gray-100 min-h-screen'>
            {dataResponse.map((products) => {
                return (
                    <div key={products.ProductID}>
                        <div>{products.ProductName}</div>
                        <div>
                            <img src={`/${products.ProductImage}`} alt=""/>
                        </div>
                        <div>{products.ProductDescription}</div>
                    </div>   
                )
            })}
        </div>
    );
}

来自api的代码,getdata.js:

import mysql from "mysql2/promise";

export default async function handler(req, res) {
    const dbconnection = await mysql.createConnection({
        host: "localhost",
        database: "onlinestore",
        port: 3306,
        user: "root",
        password: 不在此处显示但密码是有效的
    });
    try {
        const query = "SELECT ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded FROM products";
        const values = [];
        const[data] = await dbconnection.execute(query, values);
        console.log(data);
        dbconnection.end();

        data.forEach((products) => {
            products.ProductsImage = "data:image/webp;base64," + products.ProductImage;
        });

        res.status(200).json({ products: data });
    } catch (error) {
        res.status(500).json({ error: message });
    }
}

有没有人知道如何让这个工作?如何让图像显示出来?

我尝试在getdata.js中添加一些内容以将其变成一个链接,但图像仍然不会显示。

英文:

So I'm working on a project and I'm trying to pull an image that's a blob file in my database. But the image is not coming up.

Code for the first file, products.jsx:

import React from &quot;react&quot;;
import Image from &#39;next/image&#39;;
import { useEffect, useState } from &quot;react&quot;;
import { StylesContext } from &quot;@material-ui/styles&quot;;

export default function Home() {
    const[dataResponse, setdataResponse] = useState([]);
    useEffect(() =&gt; {
        async function getPageData() {
            const apiUrlEndpoint = &#39;http://localhost:3000/api/getdata&#39;;

            const response = await fetch(apiUrlEndpoint);
            const res = await response.json();
            console.log(res.products);
            setdataResponse(res.products)
        }
        getPageData();
    }, []);

    return (
        
        &lt;div className=&#39;bg-gray-100 min-h-screen&#39;&gt;
            {dataResponse.map((products) =&gt; {
                return (
                    &lt;div key= {products.ProductID}&gt;
                        &lt;div&gt;{products.ProductName}&lt;/div&gt;
                    &lt;div&gt;
                    &lt;img src={`/${products.ProductImage}`} alt=&quot;&quot;/&gt;
                    &lt;/div&gt;
                        &lt;div&gt;{products.ProductDescription}&lt;/div&gt;
               &lt;/div&gt;   
             )
            })}
    &lt;/div&gt;
);
}

Code from api, getdata.js:

import mysql from &quot;mysql2/promise&quot;;

 export default async function handler(req, res) {
    const dbconnection = await mysql.createConnection({
        host: &quot;localhost&quot;,
        database: &quot;onlinestore&quot;,
        port: 3306,
        user: &quot;root&quot;,
        password: Not showing this here, but the password works.
    });
    try {
        const query = &quot;SELECT ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded FROM products&quot;
        const values = [];
        const[data] = await dbconnection.execute(query, values);
        console.log(data);
        d
bconnection.end();

        data.forEach((products) =&gt; {
            products.ProductsImage = &quot;data:image/webp;base64,&quot; + products.ProductImage;
        }
        );
        res.status(200).json({ products: data });
    } catch (error) {
        res.status(500).json({ error: message });
    }

Does anyone know how to get this to work? How to get the image to appear?

I tried to add in something to my getdata.js to make it a link, but the image still won't appear.

答案1

得分: 1

一般规则是,将图像存储在您的关系数据库管理系统 (RDBMS) 中并不是一个好主意。这会导致数据库膨胀,而文件系统是专门设计用于提供“文件”的数据库。此外,将图像以base64编码形式传递到JSON响应中,会导致传输数据大小增加约33%。有了这些说法,我会回答您的问题。

除非在存储在数据库中时图像已经以base64编码的形式存在,否则您似乎忘记了对其进行编码。

products.ProductsImage = "data:image/webp;base64," + products.ProductImage;

应该改为:

products.ProductImage = "data:image/webp;base64," + products.ProductImage.toString('base64');

以及

<img src={`/${products.ProductImage}`} alt="" />

可以简化为:

<img src={products.ProductImage} alt="" />
英文:

As a general rule, storing images in your RDBMS is not a good idea. It causes database bloat, and the file system is a database specifically designed for serving files. Add to that, the base64 encoding of your images, to pass them in your JSON response, causes a ~33% increase in the size of the transmitted data. That said, I will answer your question.

Unless your image is already base64 encoded when stored in the database, you appear to have forgotten to encode it.

products.ProductsImage = &quot;data:image/webp;base64,&quot; + products.ProductImage;

should be:

products.ProductImage = &quot;data:image/webp;base64,&quot; + products.ProductImage.toString(&#39;base64&#39;);

And

&lt;img src={`/${products.ProductImage}`} alt=&quot;&quot;/&gt;

can be just:

&lt;img src={products.ProductImage} alt=&quot;&quot;/&gt;

huangapple
  • 本文由 发表于 2023年3月4日 03:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定