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
2 Answers
Reset to default 1I 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
版权声明:本文标题:javascript - How to decode a binary buffer to an image in node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741654094a2390652.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论