Home > Net >  download image using axios in nodejs
download image using axios in nodejs

Time:12-08

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

CodePudding user response:

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}"/>`);
});
  • Related