【问题标题】:NestJS pass downloaded file straight to clientNestJS 将下载的文件直接传递给客户端
【发布时间】:2021-04-22 16:58:11
【问题描述】:

当客户端 React 应用程序从 NestJS 服务器请求文件时,我遇到了这种情况。 NestJS 正在从另一个 API 获取此文件,因此使用 HttpService 来获取它。我不想让 Nest 应用程序保存这个文件,我只想将它直接发送给客户端,我在执行此操作时遇到了麻烦。我试过了:

return this.http
            .get(
                '[downloadURL]', this.options
            ).pipe(map(res => res.data));

但这会剥离所有文件信息,例如名称和扩展名(它是一个 zip)。

关于如何实现这一点的任何想法?

【问题讨论】:

    标签: node.js axios nestjs


    【解决方案1】:

    你可以试试这样的:

    @Get(':id/download')
        async exportDownload(
            @Param('id') id: number,
            @Res() res: Response
        ){
           res.set("Content-Type","application/zip");
           res.set("Content-Disposition","attachment; filename=file.zip");
           let zip = await this.http
                .get(
                    '[downloadURL]', this.options
                ).pipe(map(res => res.data));
           res.end(zip);
        }
    

    【讨论】:

      【解决方案2】:

      这段代码对我有用

      @Get()
      async redirectFile(@Res() res: Response) { 
          let url = 'https://sample.org/file.pdf';
          let response = await this.httpService.axiosRef(url, {
            responseType: 'stream',
          });
          response.data.pipe(res);
      }
      

      如果您在公司 http 代理后面工作,对 https url 的请求可能会挂起,在这种情况下,您可以使用 https-proxy-agent

      import { HttpsProxyAgent } from 'https-proxy-agent';
      
      @Get()
      async redirectFile(@Res() res: Response) { 
          let url = 'https://sample.org/file.pdf';
          let agent = new HttpsProxyAgent('http://host:port');
          let response = await this.httpService.axiosRef(url, {
            httpsAgent: agent,
            responseType: 'stream',
          });
          response.data.pipe(res);
          return new Promise((resolve, reject) => {
             res.on('finish', resolve);
             res.on('error', reject);
          });
      }
      

      【讨论】:

        【解决方案3】:

        对于任何通过的人,这是解决方案:

        @Get(':id/download')
            exportDownload(
                @Param('id') id: number,
                @Res() res: Response
            ): Observable<any> {
                return this.apiService.downloadExport(id).pipe(
                    map(response => response.data.pipe(res))
                );
            }
        

        【讨论】:

        • downloadExport(id) 是做什么的?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-03
        • 2018-04-29
        • 1970-01-01
        • 2011-08-15
        • 1970-01-01
        • 2016-05-02
        • 2019-04-15
        相关资源
        最近更新 更多