gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:20:33 27 4
gpt4 key购买 nike

我存储的文件类似如下:

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 }

我浏览了文档,发现它有些困惑。我做错了什么无法存储/检索文件?

最佳答案

您正在尝试读取一个空文件。检查您的代码以从磁盘加载文件并检查 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() 命令,以便您可以轻松查看问题所在。

关于node.js - 存储后如何从 MongoDB 中检索二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com