0

I want to send multipart/form-data from client via nodejs server to postgresql In nodejs I am using express-form-data module. server code:

var formData = require("express-form-data");
var BodyParser=require('body-parser');app.use(BodyParser.json()).use(formData.parse()).use(formData.format()).use(formData.stream()).use(formData.union());

app.post('/create-user',function(req,res){
var username=req.body.username;
var password=req.body.password;
..........................
var img=(req.files.pic).toString('HEX')+'\\x';
pool.query('INSERT into "Users" (username,password,"full 
name","D.O.B",emailid,sex,img) VALUES ($1,$2,$3,$4,$5,$6,$7)',
 [username,hashpass,name,dob,email,sex,img],function(err,result){ if (err) {
      res.status(500).send(err.toString());

Its obvious i have set bytea type for image data. I am tried this skiping image input and all other fields were inserted sucessfully. But i dont get the logic of inserting the image to postgres. I hav searched other stackoverflow answers nowhere i could find how to convert the image data to bytea type.My database and nodejs is set to UTF8 encoding. on converting img to hex string as shown in the code snippet i get error: invalid input syntax for type bytea

if no conversion done errors like: database server refuses to connect,nodejs console says cant set headers after they are sent.

Biboswan
  • 1,145
  • 12
  • 15

1 Answers1

0

For inserting a bytea column:

var columnDataToInsert = '\\x' + img.toString('hex');

Where img is presumably of type Buffer.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • I tried that, got error:invalid '[' hexadecimal digit . i checked console.log(img) it shows [object Object] therefore i need to parse somehow – Biboswan Jun 30 '17 at 06:17
  • @Biboswan your `img` is supposed to be of type `Buffer`, check that it is the case. – vitaly-t Jun 30 '17 at 13:58
  • Buffer.isBuffer(req.files.pic) gives false – Biboswan Jul 01 '17 at 10:38
  • @Biboswan Possibly, your `img` is a converted string already, if you are passing it in as a `Buffer`, in which case you just need to pre-pend it with `\\x`. – vitaly-t Jul 01 '17 at 12:23