0

I'm trying to create a system that would read a file from another site and serve this as a file download to the user. The file size could vary from Mbs to Gbs.

I have have already created a proof of concept using vanilla nodejs.

const app = express();
app.get('/', (req, res) => { 
    res.setHeader('Content-disposition', 'attachment; filename=FILENAME');
    res.setHeader('Content-type', 'application/octet-stream');

    http.get('URL_TO_FILE', data => {
        data.pipe(res);
    });
});

I would like to do this using loopback 4. Is this possible? Thanks!

ProNoob
  • 83
  • 1
  • 10

1 Answers1

0

You can do this easily with nodejs request and using the loopback 4 controllers. You need to import this packages:

var request = require('request');
var fs = require('fs');

And put this code in the endpoint method:

@get('/getImage')
async retrieveImage(): Promise<any> {
  let file = fs.createWriteStream(__dirname + `/file.jpg`);
  console.log('the file is here: ' + file.path);

  return await new Promise((resolve, reject) => {
    request({
      url: 'URL_TO_FILE',
      headers: {
        'Content-disposition': 'attachment; filename=FILENAME',
        'Content-type': 'application/octet-stream',
      },
      gzip: true,
    })
    .pipe(file)
    .on('finish', () => {
      console.log(`The file is finished downloading.`);
      resolve();
    })
    .on('error', (error: any) => {
        reject(error);
    })
  }).catch(error => {
    console.log(`something happened: ${error}`)
  }); 
}

From this you need to go to this url:

http://localhost:3000/getImage

And the file would be in your controllers folder with the "file.jpg" name.

  • 2
    This solution is downloading a remote file to the server. Not really what I need. What I need is the server to download the file and serve it as a file stream. I already fixed my issue above with a work around. I modified my loopback sequence to be able serve file streams. If anyone is interested, just hit me up. Will elaborate. – ProNoob Sep 17 '19 at 15:03
  • 3
    @ProNoob Why not elaborate by answering your own question? Requiring people looking for answers to contact you to get the answer kind of defeats the purpose of SO. And yes, I am interested in the answer. – Pilot_51 Dec 17 '19 at 16:14