Decode PostgreSQL bytea[] into base64 string using Javascript Buffer

96 views Asked by At

I have the following workflow from a ReactJS frontend that in the end saves an array of Blob items into a Postgresql database on a column of type bytea[].

The array object's value that is sent from React looks like:

[
   "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7TdYUGhvdG9zaG9wIDMuMAA4QklNBCUAAAAAABBPrOazmET..." ,
   "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7TdYUGhvdG9zaG9wIDMuMAA4QklNBCUAAAAAABBPrOazmET..." 
]

In the backend, the DTO that takes this value to further save into the database within the POST request looks like this:

export interface IItem extends IInteractable {
  possibleTextAnswers?: string[];
  possibleMediaAnswers?: Blob[];
}

Where the possibleMediaAnswers is the column that will save the array of Blob items.

Then, when I fetch the Item on the frontend, the object is fetched through the same DTO, and it has the value when fetched in React:

[ {type: 'Buffer', data: Array(215499)}, {type: 'Buffer', data: Array(215499)} ]

How can I decode this and get to the same values as in the beginning?

What I've tried so far:

const decodedImageSources = record.possibleMediaAnswers.map((choice) => {
      const base64String = Buffer.from(choice.data).toString('base64');
      return base64String;
})

When I check the console for the value of the base64String this is equal to: RSdceDY0NjE3NDYxM2E2OTZkNjE2NzY1MmY2YTcw...

I would expect the decoded string to also contain the data:image/jpeg;base64, part, but it doesn't.

I also tried the way: data:image/jpeg;base64,${base64String}, but the image still doesn't appear.

I assume the problem comes from here: Buffer.from(choice.data).toString('base64')? What am I doing wrong?

0

There are 0 answers