Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

download image using axios in nodejs

const {Buffer} = require("buffer")
const express = require("express");
const axios = require("axios");
const app = express();
let url =
  "https://res.cloudinary.com/practicaldev/image/fetch/s--nh8zSFgY--/c_fill,f_auto,fl_progressive,h_320,q_auto,w_320/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/285604/94170c66-2590-4002-90e0-ec4dc94ed7b5.png";

app.get("/", async(request, response) => {
  const arrayBuffer = await axios.get(url);
  let buffer = Buffer.from(arrayBuffer.data,'binary').toString("base64");
  let image = `data:${arrayBuffer.headers["content-type"]};base64,${buffer}`;
  response.send(`<img src=${image}/>`);
});

app.listen(5001, () => console.log("Server is up and running.."));

The image is not displaying. There is no error on the backend console. The buffer is a valid base64 string.

Output

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re missing two things:

1.) Add responseType: 'arraybuffer' to your request options

2.) Add the missing quotes around your base64 string to the src attribute in the img-tag:

app.get("/", async(request, response) => {
    const arrayBuffer = await axios.get(url, {
        responseType: 'arraybuffer'
    });
    let buffer = Buffer.from(arrayBuffer.data,'binary').toString("base64");
    let image = `data:${arrayBuffer.headers["content-type"]};base64,${buffer}`;
    response.send(`<img src="${image}"/>`);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading