Having trouble translating blob file into image from MySQL Database
Answered
Savannah posted this in #help-forum
SavannahOP
Hello, I save images in base64 in my database, but I can't convert them back to display.
I've attached what I get as src when I inspect the images
I've attached what I get as src when I inspect the images
Answered by Savannah
Hey bro, i did it here :
// api/internship/get/route.ts
import { promisePool } from "@/app/lib/database/db";
import { RowDataPacket } from "mysql2";
import { NextResponse } from "next/server";
import { Internship } from "@/interface/internship";
export async function GET() {
try {
const db = await promisePool.getConnection();
const selectQuery = 'SELECT * FROM internships';
const [rows] = await db.query<RowDataPacket[]>(selectQuery);
db.release();
console.log('rows :', rows);
if (rows.length > 0) {
const internships: Internship[] = rows.map(row => {
return {
...row,
images: row.images ? JSON.parse(row.images).map((img: Buffer) => img.toString('base64')) : null, // Convert Buffer to base64 string
trainings: row.trainings ? JSON.parse(row.trainings) : null,
countries: row.countries ? JSON.parse(row.countries) : null
} as Internship;
});
return NextResponse.json({ data: internships });
}
return NextResponse.json({ error: 'No internships found' });
} catch (error) {
console.error(error);
return NextResponse.json({ error: 'Failed to fetch internships' });
}
}6 Replies
Netherland Dwarf
how are you converting the images back?
@Netherland Dwarf how are you converting the images back?
SavannahOP
Hey bro, i did it here :
// api/internship/get/route.ts
import { promisePool } from "@/app/lib/database/db";
import { RowDataPacket } from "mysql2";
import { NextResponse } from "next/server";
import { Internship } from "@/interface/internship";
export async function GET() {
try {
const db = await promisePool.getConnection();
const selectQuery = 'SELECT * FROM internships';
const [rows] = await db.query<RowDataPacket[]>(selectQuery);
db.release();
console.log('rows :', rows);
if (rows.length > 0) {
const internships: Internship[] = rows.map(row => {
return {
...row,
images: row.images ? JSON.parse(row.images).map((img: Buffer) => img.toString('base64')) : null, // Convert Buffer to base64 string
trainings: row.trainings ? JSON.parse(row.trainings) : null,
countries: row.countries ? JSON.parse(row.countries) : null
} as Internship;
});
return NextResponse.json({ data: internships });
}
return NextResponse.json({ error: 'No internships found' });
} catch (error) {
console.error(error);
return NextResponse.json({ error: 'Failed to fetch internships' });
}
}Answer
SavannahOP
And more precisely, like that :
images: row.images ? JSON.parse(row.images).map((img: Buffer) => img.toString('base64')) : null, // Convert Buffer to base64 string`And this is the data i get when i fetch the route
It's good, i fix the problem, thanks @Netherland Dwarf 😉