Home > Enterprise >  Unable to convert url image response to buffer using nodejs
Unable to convert url image response to buffer using nodejs

Time:03-22

I am working on downloading image from url using nodejs. But I am unable to convert response to buffer. Image I receive from response is in gibberish form.. Following is my code:

app.get('/test', async (req, res) => {
  const data = await fetch("https://api.image/test.jpg");
  res.send(Buffer.from(data));
});

Response of fetch API is: enter image description here

Error after downloading image is:

Image is

I also tried following buffer encoding but I still getting above error after downloading image:

 Buffer.from(data,'base64');
 Buffer.from(data,'ascii');
 Buffer.from(data,'base64url');
 Buffer.from(data,'binary');
 Buffer.from(data,'hex');
 Buffer.from(data,'latin1');
 Buffer.from(data,'ucs-2');
 Buffer.from(data,'ucs2');
 Buffer.from(data,'utf-8');
 Buffer.from(data,'utf16le');
 Buffer.from(data,'utf8');

CodePudding user response:

I think this should be like:

app.get('/test', async (req, res) => {
  const data = await fetch("https://api.image/test.jpg");
  res.send(Buffer.from(await data.arrayBuffer()));
});
  • Related