skip to Main Content

So. I am adding record to a database (MySQL with XAMPP and "mysql2": "^3.6.2" package) by

export const addPage = async (req,res) => {
        try
        {
            if(req.session.user !== undefined)
            {
                const body = req.body;
                const plik =  req.file.buffer.toString('utf-8'); // REMEMBER THIS
                const link = body.link;
                const tytul = body.tytul;
                const opis = body.opis;
                const user =  req.session.user.substr(-1);
                const curDate = new Date();
                const [re] = await (global.db).query("INSERT INTO sites VALUES (NULL, ?, ?, ?, ?, ?, ?);", [plik, link, tytul, opis, user, curDate]);
                res.redirect("/panel")
                return 0;
            }
            else{res.redirect('/');}
        }
        catch(err)
        {
            throw err; res.redirect('/login');
        }
}

I wanted to do an api that gets all records. So I did

export const getAllPages = async (req,res) => 
{
    try
    {
        var [rows,fields] = await (global.db).query("select * from sites order by creation_date");
        var image_array = [];

        rows.forEach(element => {
            image_array.push(element.icon.toString('base64'))
        });


       res.status(201).json({
            status:"success",
            Length: rows.length,
            data: rows,
            images: image_array
        });
    }
    catch(err)
    {
        res.status(401).json({
                status:"fail",
                message: err.message
        }) 
    }
}

Note: (global.db) id variable that holds connection to database it works well, no issues with that. But I have object consisting of status, length of data, data itself (consisting of records from database), and images which consist of array of blobs transfered into string of base64.

In my js file in Frontend I have:

const PagesData = fetch("http://localhost:3000/api/v1/Pages", { method:"GET"}) 
    .then((r) => r.json())
    .then((Data) => {
        console.log(Data);
        for (let i = 0 ; i < Data.Length; i++)
        { 
            let element = Data.data[i]
            console.log(element)

            document.getElementsByTagName('main')[0].innerHTML+=
            `
                    <a class="window octagon-border" href="sitedetails/${element.id}">
                        <div class="window-img">
                            <img id="${i}"/>
                        </div>
                        <div class="window-title">
                            <div class="btn inverted-colors no-hover">${element.title}</div>
                        </div>
                        <div class="window-mask hexagon"></div>
                    </a>
            `
        };   
        for(let i = 0; i< Data.Length; i++)
        {
            document.getElementById(i).src = Data.images[i];
        }     
    })
    .catch((e) =>  console.log(e));

And I get back the result that in img tag I get src="" and there is a long string in it (it has characters, not only numbers so conversion to string(‘base64’) worked). The problem is that it does not show the result (it does not display and image, but an icon in browser that there is no file like that).

There might be a problem that into databse i put utf-8 conversion and when geting data from database i use base64, but when into database I used base 64 then it didn’t work.

I want to get image from blob and then display it in img tag

I use node v20.5.1

2

Answers


  1. Chosen as BEST ANSWER

    Author here. I was right that encoding was a problem. Changes that I made

    From:

    const plik = req.file.buffer.toString('utf-8');
    

    To:

    const plik =  req.file.buffer;
    

    And in frontend

    From:

    document.getElementById(i).src = Data.images[i];
    

    To:

    document.getElementById(i).src = "data:image/png;base64,"+Data.images[i];
    

  2. I don’t fully understand the DB part, but regarding the blob on the frontend side:

    • At the part where you expect the blob, return response as response.blob() not response.json(). Basically, try this:
    return response.blob().then(result =>{
      const img = URL.createObjectURL(result)
      const myImgTag = document.querySelector(".my-img-tag")
      myImgTag.src = img
    })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search