简体   繁体   中英

How to save pdf file in mysql with node.js?

I am using node.js with mysql, and I want to save pdf file which downloads from url and save it in database. I have written my code here.

exports.pdf = function(req, response) {    
  var url ="http://www.ieee.org/documents/ieeecopyrightform.pdf";
  http.get(url, function(res) {
   console.log("sss");
   var chunks = [];
   res.on('data', function(chunk) {
    console.log('start');
    chunks.push(chunk);
   });
  res.on("end", function() {
    console.log('downloaded');
    var jsfile = new Buffer.concat(chunks);
    console.log('converted to base64');
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "X-Requested-With");
    response.header('content-type', 'application/pdf');
  });
  }).on("error", function() {
  console.log("error");
  }); 
}

The mysql / mysql2 modules support Blob/binary column types, so for those modules all you have to do is pass in the Buffer instance as the column value. For example:

// ...
// no need for `new` with `Buffer.concat()`
var jsfile = Buffer.concat(chunks);
var query = 'INSERT INTO `files` SET ?',
    values = {
      type: 'pdf',
      data: jsfile
    };
mysql.query(query, values, function(err) {
  if (err) throw err; // TODO: improve
  // do something after successful insertion
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM