最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Nodejs - Fetch file from url and send content to client - Stack Overflow

programmeradmin2浏览0评论

For some reason, I don't want to share the URL public (sercet url),

My workflow is as below:

Client send API request to my server:

Api: mywebsite/api/image_abc.jpg

I have Nodejs express server to fetch the file from the url:

Eg: sercret_url/image_abc.jpg

And then from response image content from Nodejs, I send back the image content to the client and display as image_abc.jpg

I looked around on stackoverflow, but just got an answer from reading file from disk and send to client. What I want is just redirect the image content to client, not saving file to the disk.

Thank you.

For some reason, I don't want to share the URL public (sercet url),

My workflow is as below:

Client send API request to my server:

Api: mywebsite./api/image_abc.jpg

I have Nodejs express server to fetch the file from the url:

Eg: sercret_url./image_abc.jpg

And then from response image content from Nodejs, I send back the image content to the client and display as image_abc.jpg

I looked around on stackoverflow, but just got an answer from reading file from disk and send to client. What I want is just redirect the image content to client, not saving file to the disk.

Thank you.

Share Improve this question asked Jan 12, 2022 at 6:44 Thuan ThienThuan Thien 372 silver badges6 bronze badges 1
  • 1 Do i understand that you want to fetch your file from an URL and return to the client as a buffer ? – nermineslimane Commented Jan 12, 2022 at 10:03
Add a ment  | 

1 Answer 1

Reset to default 6

Assuming you want to return the contents of a file from a certain URL to the client as buffer here's the solution I suggest

Get the file using axios and return the buffer to you client

  const axios = require('axios');
  let URL='some-valid-url'
  const response = await axios.get(
    URL,
    { responseType: 'arraybuffer' }
  );
  const buffer = Buffer.from(response.data, 'utf-8');
  res.status(200).send(buffer);

In case you want to save it to your server you can use fs as follows to write the file to the folder of your choice

  fs.writeFile(fileName, buffer, (err) => {
      if(!err) console.log('Data written');
    });
发布评论

评论列表(0)

  1. 暂无评论