如何在Loopback 4上流式下载文件? [英] How to stream file as download on Loopback 4?

查看:223
本文介绍了如何在Loopback 4上流式下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个系统,该系统将从另一个站点读取文件并将其作为文件下载提供给用户. 文件大小可能从Mbs到Gbs不等.

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.

我已经使用香草nodejs创建了概念证明.

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);
    });
});

我想使用回送4做到这一点.这可能吗?谢谢!

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

推荐答案

您可以使用 nodejs轻松完成此操作请求并使用回送4控制器. 您需要导入以下软件包:

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

该文件将以"file.jpg"名称保存在您的控制器文件夹中.

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

这篇关于如何在Loopback 4上流式下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆