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

前端之家收集整理的这篇文章主要介绍了node.js – 如何在存储后从MongoDB中检索二进制文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我存储的文件类似于以下内容
  1. var pdfBinary = fs.readFileSync("myfile.pdf");
  2. var invoice = {};
  3. invoice.pdf = new mongo.Binary(pdfBinary);

然后我将上面的文档插入MongoDB.然后我尝试检索它类似于以下内容

  1. collection.findOne({},function(err,retrievedPDF) {
  2. fs.writeFile("myretrieved.pdf",retrievedPDF.pdf.buffer,function(err) {
  3. ....
  4. });
  5.  
  6. });

它作为零字节文件出现.如果我在console.log中存储文件,它看起来如下所示:

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

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

解决方法

你正在尝试读取一个空文件.检查代码以从磁盘加载文件并检查PDF文件.

空二进制文件将如下所示:

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

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

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

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

  1. var fs = require('fs');
  2. var mongo = require('mongodb').MongoClient;
  3.  
  4. var pdfBinary = fs.readFileSync("testout.pdf");
  5. // print it out so you can check that the file is loaded correctly
  6. console.log("Loading file");
  7. console.log(pdfBinary);
  8.  
  9. var invoice = {};
  10. invoice.pdf = new mongodb.Binary(pdfBinary);
  11. // set an ID for the document for easy retrieval
  12. invoice._id = 12345;
  13.  
  14. mongo.connect('mongodb://127.0.0.1:27017/test',db) {
  15. if(err) console.log(err);
  16.  
  17. db.collection('invoices').insert(invoice,doc){
  18. // check the inserted document
  19. console.log("Inserting file");
  20. console.log(doc);
  21.  
  22. db.collection('invoices').findOne({_id : 12345},doc){
  23. if (err) console.error(err);
  24. fs.writeFile('testout.pdf',doc.pdf.buffer,function(err){
  25. if (err) throw err;
  26. console.log('Sucessfully saved!');
  27. });
  28. });
  29. });
  30. });

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

猜你在找的Node.js相关文章