Convert Base64 image to raw binary with Node.js

前端 未结 2 1111
北荒
北荒 2021-02-14 12:42

I have found posts that are close to what I\'m looking for, but I have not been able to successfully implement what I want. Here is the general flow:

  1. Submit photo
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-14 13:31

    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); 
    
      });
    });
    

提交回复
热议问题