PostgreSQL - How to insert Base64 images strings i

2019-07-31 11:20发布

问题:

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.

回答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