For larger images you should use file system but for small images like thumbnails that's how i handle it with typeorm
@Column({ type: "longblob" })
thumbnail: string;
By the way you should run this commands in a mysql console connected to that same server to avoid any package size errors
set global net_buffer_length=1000000;
set global max_allowed_packet=1000000000;
and I converted image to base64 string with built-in FileReader API
// file param is coming from html input element
const reader = new FileReader();
// use try-catch because if user don't select a file it throws an error
try {
reader.onloadend = (e) => {
const base64string = e.target.result;
sendImageToServer(base64string);
}
}
reader.readAsDataURL(file);
} catch (error) {
console.log(error);
}
When you are sending thumbnail to client it converts it to a buffer object (ex. \
{
type: "Buffer",
data: [
// Uint8Array
]
}
so we need to convert it base64 string again
// This 'toString' function will convert buffer array to base64 string
const thumbnail = Buffer.from(recipe.thumbnail).toString();
sendDataToClient(thumbnail);
Then displaying image is very easy
// If you're using react like me you can do it like that
<img src={base64stringFromServer} alt="thumbnail" />
// otherwise just select img tag with query selector then set 'src' attribute to 'base64stringFromServer
// and find a better variable name then this :)
I think that's the best way to store images at database.