GPinskiy GPinskiy - 1 month ago 9
Javascript Question

toString('base64') In Node Returns Invalid Image Data

I currently have a website where I send a

GET
request to the server and expect it to download an image from a website and send the data back to the client. If I write the resulting data from the download directly to a file, it works.

app.get('/image', function(req, res) {
request("http://ipcam/auto.jpg", {encoding: 'binary'}, function(err, response, body) {
if (err) res.send(err);
fs.writeFile('logo ' + (Math.random() * 1000).toFixed(0) + '.jpeg', body, 'binary', function(err){
if (err) throw err
console.log('File saved.')
})
res.send(200);
});
});


However, when I try to convert it to base64 using a
Buffer
object and then send it to the client, the
img
tag does not recognize it as valid image data. This was confirmed using online utilites that show a preview of base64 image data.

Server:

res.send(new Buffer(body.replace(/(\r\n|\n|\r)/gm,""), 'binary').toString('base64'));


Client:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && xmlHttp.responseText != undefined) {
var base64string = xmlHttp.responseText.replace(/(\r\n|\n|\r)/gm,"");
document.getElementById('image').src = 'data:image/jpeg;base64,' + base64string;
}
};
xmlHttp.open("GET", '/image', true);
xmlHttp.send();


Edit: I removed the regex that removed the line breaks as pointed out. It did not help however.

Current Server:

res.send(new Buffer(body, 'binary').toString('base64'));


Current Client:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && xmlHttp.responseText != undefined) {
document.getElementById('image').src = 'data:image/jpeg;base64,' + xmlHttp.responseText;
}
};
xmlHttp.open("GET", '/image', true);
xmlHttp.send();

Answer

{encoding: 'binary'}

AFAIK if you want request to interpret response as a binary data, you should specify encoding: null instead.

(cite)

encoding - Encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)

Once you do so the body you get in the response will be set to Buffer already, so you can just directly do:

body.toString('base64')
Comments