在Nest中如何将axios获取的文件流转发并返回给前端?
Nest框架返回外部文件流到前端的实现方案
前置配置
调用axios获取外部资源时,必须添加responseType: 'stream'配置,确保接口返回的是可读流对象,而非序列化后的Buffer或文本内容。
实现方式1:使用Express原生响应对象
这种方式灵活性更高,适合需要自定义响应逻辑的场景:
import { Controller, Get, Res } from '@nestjs/common'; import { Response } from 'express'; import axios from 'axios'; @Controller('file') export class FileController { @Get('download') async downloadExternalFile(@Res() res: Response) { // 请求外部资源获取流 const externalResponse = await axios({ method: 'GET', url: '你的外部资源地址', responseType: 'stream' }); // 透传响应头,也可根据业务需求自定义 res.setHeader('Content-Type', externalResponse.headers['content-type']); // 配置为attachment强制浏览器触发下载,filename可自定义文件名称 res.setHeader('Content-Disposition', 'attachment; filename="custom_name.file"'); res.setHeader('Content-Length', externalResponse.headers['content-length']); // 直接将外部流管道传输到前端响应 externalResponse.data.pipe(res); } }
实现方式2:使用Nest内置StreamableFile类
这种方式更符合Nest的开发规范,不需要手动注入原生响应对象:
import { Controller, Get, StreamableFile } from '@nestjs/common'; import axios from 'axios'; @Controller('file') export class FileController { @Get('download') async downloadExternalFile() { const externalResponse = await axios({ method: 'GET', url: '你的外部资源地址', responseType: 'stream' }); // 直接返回StreamableFile实例,Nest会自动处理流传输和响应头 return new StreamableFile(externalResponse.data, { type: externalResponse.headers['content-type'], disposition: 'attachment; filename="custom_name.file"', length: parseInt(externalResponse.headers['content-length']) }); } }
注意事项
- 若需要让浏览器直接预览文件(比如图片、PDF),将
Content-Disposition的attachment改为inline即可 - 不要将流全部读取为Buffer后再返回,大文件场景会导致服务端内存溢出,直接管道传输流是最优方案
- 可给外部可读流添加
error事件监听,处理外部资源请求中断、超时等异常场景,避免内存泄漏
内容的提问来源于stack exchange,提问作者hywel
相关产品推荐
相关产品推荐

