I want to store PDF using postgresql bytea in Node.js

1.4k views Asked by At

I want to store PDF using PostgreSQL bytea in Node.js

How can I convert PDF to datatype bytea ?

My code is:

request.get('https://www.cbconnexus.com/upload/settings/black/data.pdf', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString('base64');
        console.log(data);
    }
});
1

There are 1 answers

0
Gerard H. Pille On BEST ANSWER

A node http server accepting a post of a PDF and storing it in a postgresql table. Listens on fixed IP address 192.168.1.3, port 8888 by default but you can specify the port as the first parameter. Uses pg and formidable.

var myArgs = process.argv.slice(2);
var http = require('http');
var fs = require('fs');
var port = 8888;

const { IncomingForm } = require('formidable');

const { Client } = require('pg');
const dbc = new Client({
    host: '127.0.0.1',
    user: 'ghp',
    password: 'zevrepdm',
    database: 'ghp',
    port: 5434,
  });
dbc.connect();

if (myArgs[0]) {
  port = myArgs[0];
}

http.createServer(function (req, res) {
  const chunks = [];

  if (req.url === '/' && req.method.toLowerCase() === 'post') {
      const form = new IncomingForm({ multiples: true });
      form.parse(req, (err, fields, files) => {
        if (files.userfile.type == "application/pdf") {
          var rawData = fs.readFileSync(files.userfile.path) ;
          dbc
            .query(
              'insert into files(name,type,size,data) values ($1,$2,$3,$4)'
              + ' returning name',
              [ files.userfile.name, files.userfile.type, files.userfile.size,
                rawData ]
            ).then(res => {
                var insMessage = 'file ' + res.rows[0].name + ' inserted' ;
                console.log( insMessage );
            }).catch(err => {
                var insMessage = 'Error inserting file ' + files.userfile.name ;
                console.error( insMessage );
                console.error( err.stack );
            });
        }
      });
  }
  req.on('data', chunk => chunks.push(chunk));
  req.on('end', () => {
    res.writeHead(200, [['Content-Type', 'text/html'],
                      ['Cache-Control', 'maxage=120, s-maxage=60, public'],
                      ['X-Accel-Expires', '86400'],
                      ['X-BEVar', req.url] ]);
    res.write('Hello ' + req.headers['user-agent'] + '!<br>');
    res.write('<br>I\'m the one listening on port ' + port + '!<br>');
    res.write("  <FORM ACTION='");
    res.write(req.url);
    res.write("' METHOD='post' enctype='multipart/form-data'> \
                  <input type='hidden' name='MAX_FILE_SIZE' value='128000000'> \
                  <input name='userfile' type='file' size='50'> \
                  <input type='submit' value='Send File'> \
                 </FORM>");
    res.end('Do you know it\'s already ' + Date() + '?');
  })
}).listen(port,"192.168.1.3");