简体   繁体   English

如何使用node.js在MySQL中保存PDF文件?

[英]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. 我正在使用带有MySQL的node.js,我想保存从url下载的pdf文件并将其保存在数据库中。 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. mysql / mysql2模块支持Blob / binary列类型,因此对于这些模块,您要做的就是将Buffer实例作为列值传递。 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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