Jon Sud
Jon Sud

Reputation: 11671

How to download file from url using express?

I have a image file "https://cdn.my.com/image1.png".

I want to create a proxy to this url from my api.

api.get('/download', (req, res) => {

 const url = "https://cdn.my.com/image1.png";

 res.download(url);
});

I think download is need a file location as argument and not url.

How I can download url as proxy? (I don't want to wait to download to complete and send the response after)

Upvotes: 2

Views: 2797

Answers (2)

Nyi Nyi
Nyi Nyi

Reputation: 966

const path = require('path');

api.get('/download', (req, res) => {
    res.download(path.join(__dirname, 'image1.png'));
}); 

Let 'image1.png' file and js file to be in same directory

Upvotes: 0

eol
eol

Reputation: 24565

You need to request the file first and then pipe the response to the res-object. Something like this:

const request = require('superagent')

api.get('/download', (req, res) => {
   res.set(
     'Content-Disposition',
     'attachment; filename=some_file_name.png'
   );

   request("https://cdn.my.com/image1.png").pipe(res);
});

Upvotes: 5

Related Questions