Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 236
Rahul Avatar asked Oct 15 '25 11:10

Rahul


1 Answers

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}"/>`);
});
like image 107
eol Avatar answered Oct 18 '25 02:10

eol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!