admin管理员组

文章数量:1300068

I'm receiving an image in a binary stream as shown below, however when I try to create a buffer with the following data the buffer appears to be empty. Is the problem that buffer doesn't understand this format?

V�q)�EB\u001599!F":"����\u000b��3��5%�L�\u0018��pO^::�~��m�<\u001e��L��k�%G�$b\u0003\u0011���=q�V=��A\u0018��O��U���m�B���\u00038�����0a�_��#\u001b����\f��(�3�\u0003���nGjr���Mt\�\u0014g����~�#�Q�� g�K��s��@C��\u001cS�`\u000bps�Gnzq�Rg�\fu���C\u0015�\u001d3�E.BI\u0007���

var buffer = new Buffer(req.body, 'binary')
    console.log("BUFFER:" + buffer)
fs.writeFile('test.jpg', buffer, function(err,written){
   if(err) console.log(err);
    else {
     console.log("Successfully written");
    }
});

I'm receiving an image in a binary stream as shown below, however when I try to create a buffer with the following data the buffer appears to be empty. Is the problem that buffer doesn't understand this format?

V�q)�EB\u001599!F":"����\u000b��3��5%�L�\u0018��pO^::�~��m�<\u001e��L��k�%G�$b\u0003\u0011���=q�V=��A\u0018��O��U���m�B���\u00038�����0a�_��#\u001b����\f��(�3�\u0003���nGjr���Mt\�\u0014g����~�#�Q�� g�K��s��@C��\u001cS�`\u000bps�Gnzq�Rg�\fu���C\u0015�\u001d3�E.BI\u0007���

var buffer = new Buffer(req.body, 'binary')
    console.log("BUFFER:" + buffer)
fs.writeFile('test.jpg', buffer, function(err,written){
   if(err) console.log(err);
    else {
     console.log("Successfully written");
    }
});
Share Improve this question edited Oct 1, 2015 at 14:26 Harald K 27.1k7 gold badges69 silver badges115 bronze badges asked Sep 30, 2015 at 23:41 Sarodh UggallaSarodh Uggalla 3031 gold badge4 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

I think you should set the encoding when you call fs.writeFile like this :

fs.writeFile('test.jpg', buffer, 'binary', function(err) {

Problem was body-parser doesn't parse content-type: octet-stream and I was overriding the header to parse it as an url-encoded-form which the buffer didn't understand even though I was able to log the req.body. The middleware below allows for the parsing of content-type: octet-stream for body-parser.

app.use(function(req, res, next) {
   var contentType = req.headers['content-type'] || ''
   var mime = contentType.split(';')[0];
    // Only use this middleware for content-type: application/octet-stream
    if(mime != 'application/octet-stream') {
        return next();
    }
   var data = '';
   req.setEncoding('binary');
    req.on('data', function(chunk) { 
       data += chunk;
   });
   req.on('end', function() {
      req.rawBody = data;
      next();
  });
});

本文标签: javascriptHow to decode a binary buffer to an image in nodejsStack Overflow