简体   繁体   中英

Nodejs image not converting to base64 correctly

So i'm reading a file, and saving the file into a variable. I then create a buffer using the variable and convert it to a base64 string, to display in an <img> element. But when its generated it dosen't look like a base64 string, and it dosen't display on the page.

I am reading the png file using fflate

    async readFile (name: string) {
        return new Promise((resolve) => {
            const file = this.getFile(name);
            if (!file) return resolve(null);
    
            const filedata: string[] = [];
            const decoder = new DecodeUTF8();
            file.ondata = (err, data, final) => {
                decoder.push(data, final);
            }
            decoder.ondata = (str, final) => {
                filedata.push(str);
                if (final) resolve(filedata.join(''));
            }
            file.start();
        })
    }
const avatar = await readFile('avatar.png');
const avatar_64 = Buffer.from(avatar).toString('base64');
console.log(avatar);
console.log(avatar_64)
<img alt="User Avatar" src={`data:image/png;charset=utf-8;base64,${avatar_64}`}/>

Browser Console

Is this how it's supposed to look? I've already tried putting the charset into the img uri, but that dosen't seem to work

I can confirm that it works with this png file: ( https://flatbay.fr/img/seloger.png )

let avatar = require('fs').readFileSync('./seloger.png');
const avatar_64 = Buffer.from(avatar).toString('base64');
// console.log(avatar);
// console.log(avatar_64)
console.log('<img alt="User Avatar" src="data:image/png;charset=utf-8;base64,'+avatar_64+'"/>');

Can you try with my picture? or give me yours? Or maybe the way you get avatar populated is the problem?

the fact that u use react should not be a problem IMHO. syntax looks valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM