如何在存储后从MongoDB中检索二进制文件?

时间:2014-06-28 23:58:44

标签: node.js mongodb

我存储的文件类似于以下内容:

var pdfBinary = fs.readFileSync("myfile.pdf");
var invoice = {};
invoice.pdf = new mongo.Binary(pdfBinary);

然后我将上述文档插入MongoDB。然后我尝试检索它类似于以下内容:

    collection.findOne({}, function(err, retrievedPDF) {
        fs.writeFile("myretrieved.pdf", retrievedPDF.pdf.buffer, function(err) {
            ....
        });

    }); 

它以零字节文件形式出现。如果我在console.log中存储的文件如下所示:

{ pdf: 
 { _bsontype: 'Binary',
   sub_type: 0,
   position: 0,
   buffer: <Buffer > },
_id: 53af545681a59758611937d7 }

我已经阅读了文档,我发现它有些令人困惑。我无法存储/检索文件,我做错了什么?

2 个答案:

答案 0 :(得分:8)

您正在尝试读取空文件。检查代码以从磁盘加载文件并检查PDF文件。

空二进制文件如下所示:

> console.log(new mongodb.Binary(""));
{ _bsontype: 'Binary',
  sub_type: 0,
  position: 0,
  buffer: <Buffer > }

具有内容的二进制文件看起来像:

{ _bsontype: 'Binary',
     sub_type: 0,
     position: 7867,
     buffer: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 c3 a4 c3 bc c3 b6 c3 ...> }

这是一个适合我的完整示例:

var fs = require('fs');
var mongo = require('mongodb').MongoClient;

var pdfBinary = fs.readFileSync("testout.pdf"); 
// print it out so you can check that the file is loaded correctly
console.log("Loading file");
console.log(pdfBinary);

var invoice = {};
invoice.pdf = new mongodb.Binary(pdfBinary);
// set an ID for the document for easy retrieval
invoice._id = 12345; 

mongo.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
  if(err) console.log(err);

  db.collection('invoices').insert(invoice, function(err, doc){
    // check the inserted document
    console.log("Inserting file");
    console.log(doc);

    db.collection('invoices').findOne({_id : 12345}, function(err, doc){
      if (err) console.error(err);
      fs.writeFile('testout.pdf', doc.pdf.buffer, function(err){
          if (err) throw err;
          console.log('Sucessfully saved!');
      });
    });
  });
});

我添加了console.log()命令,因此您可以轻松查看问题所在。

答案 1 :(得分:2)

当然看起来保存中出了问题。以下是一个完整的工作示例,可用于比较:

var fs = require('fs'),
    mongo = require('mongodb'),
    MongoClient = mongo.MongoClient,
    ObjectId = mongo.ObjectID,
    Binary = mongo.Binary;


MongoClient.connect('mongodb://localhost/fs',function(err,db) {

  var name = "receptor.jpg";
  var binData = fs.readFileSync(name);
  var object = {};
  object.name = name;
  object.data = new Binary(binData);

  db.collection("test").findAndModify(
    { name: name },
    [],
    object,
    { upsert:true },
    function(err,data,newObj) {

      if ( data == null ) {
        console.log(newObj);
      } else {
        console.log(data);
      }

      db.collection("test").findOne({ name: name },function(err,data) {

        fs.writeFile("ouput.jpg",data.data.buffer,function(err) {
          console.log("done");
        });
    });
  });
});
相关问题