Handle image/jpeg response and display on UI by base64 encode in NodeJS

2.1k Views Asked by At

Using NodeJs request module, I made a request to the server and receive a response like that:

response.body = "����JFIF��C..."

response.headers["content-type"] = image/jpeg

I try to convert it to base64 encode with below code:

let imageData = "data:" + response.headers["content-type"] + ";base64," + new Buffer(response.body).toString('base64');
// "data:image/jpg;base64,77+977+977+977+9ABBKRklGAAEBAAABAAEAAO...";

After that, set it to an tag to display on UI like that:

        var image = new Image();
        image.src = response.imageData;

But the UI show break image like: enter image description here

If I go to the request URL directly, I still see the correct image. I think there is something wrong with convert base64 method, but I don't know how to fix it.

Please help me. Thank you.

1

There are 1 best solutions below

1
On

I found the mistake. Just use request with encoding null and everything works smoothly.

var request = require('request').defaults({ encoding: null });

Ref: Node.js get image from web and encode with base64