6

I have the following SQL:

CREATE TABLE Documents (
  Id INT NOT NULL,
  UserId INT NOT NULL,
  Label CHARACTER VARYING(220) NOT NULL,
  Image BYTEA NOT NULL,
  PRIMARY Key(Id),
  FOREIGN KEY (UserId) REFERENCES Users(Id)
);

I want to know, How should I have to insert the Base64 image into the table.

The Base64 string comes from a Buffer from after getting the image using the fs module on Node.js.

I'm attempting to insert the image using raw queries of Sequelize, but I have not found proper information on this.

user871611
  • 3,307
  • 7
  • 51
  • 73
  • How do you want to insert the Base64 image? Via SQL statement? Programmatically? – user871611 Mar 14 '19 at 19:38
  • Programmatically, using [Sequelize's](http://docs.sequelizejs.com/) raw queries... I extracted the base64 string from a Buffer using the file system (**fs**) package in Node.js –  Mar 14 '19 at 19:41
  • You may add this useful information to your question. – user871611 Mar 14 '19 at 19:45
  • @user871611 I added it, of course I did have to add it in the first place, but due to the lack of info I found on how to insert to the bytea I thought that just asking on the SQL query would be enough, thanks for your patience –  Mar 14 '19 at 19:53
  • Shouldn't the `decode` function (see https://www.postgresql.org/docs/9.1/functions-binarystring.html) do the trick? Something like `decode(..., 'base64')`. – user871611 Mar 14 '19 at 20:06
  • The first parameter should be my base64 plain string? –  Mar 14 '19 at 20:13
  • Yes. Read the manual in the link I provided. – user871611 Mar 14 '19 at 20:38

2 Answers2

9

Try this:

insert into table_name (image)
values decode('AcAAFBAO5Az....AQAAAFBCO5gT/AEAABT', 'base64')

Here is some information about decode

https://www.base64decode.net/postgresql-decode

efirat
  • 3,679
  • 2
  • 39
  • 43
1

To answer the question regarding Postgres and Sequelize:

You will need to use the Sequelize.BLOB('tiny') datatype to model a BYTEA Postgres datatype.

Here is more information about datatypes in Sequelize (it also contains the above information):

http://docs.sequelizejs.com/manual/data-types.html

When converting into a tiny blob, Postgres will default to utf-8, meaning you'll probably want to turn your data into a utf-8 encoding, store the data, and the read it as utf-8.

EDIT:

You will use Base64 to encode the image binary data into an ASCII string: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

David Kamer
  • 2,677
  • 2
  • 19
  • 29