Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle blob column in TypeORM

I have a MySQL database that stores profile images of users. The user info should be provided via REST API that is implemented as a Node.js server. I use TypeORM for accessing the database.

I want to deliver the image info as base64 string via REST API. How could I achieve this?

I mapped the blob column as a Buffer in my entity. Do I have to convert the data to base64 using a listener on the property?

like image 268
Ralf Schneider Avatar asked Oct 20 '25 09:10

Ralf Schneider


2 Answers

For a cleaner code, you can try using a transformer. Here's a usage example for saving and retrieving a string from a blob column.

  @Column({
    transformer: {
      to: (value: string) => Buffer.from(value),
      from: (value: Buffer) => value.toString()
    }
   })
  longText?: string;
like image 194
Andrei Avatar answered Oct 22 '25 00:10

Andrei


I found the solution that works for me:

I load the user object and the image is loaded into a string variable. Before I deliver the object I convert it into a Buffer and encode it base64:

Buffer.from(user.profileImage).toString('base64');
like image 33
Ralf Schneider Avatar answered Oct 21 '25 23:10

Ralf Schneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!