Convert Base64 image to raw binary with Node.js

為{幸葍}努か 提交于 2019-12-03 12:40:50

You can take the string from MongoDB, create a new buffer instance, and specify an encoding when doing so. The resultant buffer will be in binary data.

var b64str = /* whatever you fetched from the database */;
var buf = new Buffer(b64str, 'base64');

So in your implementation:

server.get(version+'/images/:id', function(req, res) {
  gridfstore.read(req.params.id, function(err, data) {
    var img = new Buffer(data.buffer, 'base64');

    res.writeHead(200, {
      'Content-Type': 'image/jpeg',
      'Content-Length': img.length
    });
    res.end(img); 

  });
});

Make sure your string is correct. This worked for me..

var buf = new Buffer(b64stringhere, 'base64');
var express = require('express'), app = express();
app.get('/img', function(r, s){
    s.end(buf);
})
app.listen(80);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!