0

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");
  }); 
}
1
  • 1
    What have you tried? How are you connecting to MySQL? You haven't included any of your database code. Commented Sep 23, 2014 at 16:45

1 Answer 1

2

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.