How to stream file as download on Loopback 4?

冷暖自知 提交于 2020-06-17 13:07:28

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/57318398/how-to-stream-file-as-download-on-loopback-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!