I am new to mongodb.
I stored binary data with below code snippet:
var data = fs.readFileSync(path);
var image = new mongodb.Binary(data);
//open connection/collection
var record = {picname: id, content: image };
collection.save(record, {safe: true}, function(err,result){
if(err)
console.log(err.stack);
});//save
I can see the record size in db. there is binary data. record size also matched with file size. am happy.
Now, retrieved same binary data from mongo and trying to send it in response:
var record = {picname: id};
collection.findOne(record, function(err,result){
if(err)
console.log(err.stack);
else
{
console.log('before read from db for download.');
//HOW TO READ IMAGE/BINARY DATA FROM RESULT?
//I need to send result in response. Any Idea?
console.log('before read from db for download');
}
});
I am sending binary data with below code snippet. It's not working for all the files. What could be the issue:
collection.findOne(record, function(err,result){
if(err)
console.log(err.stack);
else
{
console.log('before read from db for download. result: [' + result.picname + " ], type: " + result.imagetype);
res.end(result.content.buffer, "binary");
console.log('Responded SUCCESS: ' + id );
}
});//findOne
Please let me know how to retrieve and send via response.
Thanks in advance DD.
Your problem here is not so much with storing and reading the data, but is actually all about content types. So ideally you want to store this with your data as well as return the correct header information when you send the response.
So part of this would be mime type detection. There are modules available, mmmagic is one of them
var Magic = require('mmmagic').Magic;
var magic = new Magic();
var data = fs.readFileSync(path);
var image = new mongodb.Binary(data);
//open connection/collection
magic.detect(data,function(err,result) {
var record = {picname: id, content: image, mimeType: result };
collection.save(record, {safe: true}, function(err,result){
if(err)
console.log(err.stack);
});//save
});
Methods for writing the header vary, but with the base "http" for node you call as shown:
var record = {picname: id};
collection.findOne(record, function(err,result){
if(err)
console.log(err.stack);
else {
res.writeHead(200, {
'Content-Type': result.mimeType,
'Content-Length': result.content.length
});
res.write(result.content.buffer);
res.end();
}
});
So what effectively gets returned here is the binary data identified by it's correct mime type. So you can access this from an URL where you supply the means to lookup the document and view directly in a browser just as if it was a regular image file being served.