有时您可能希望将文件从 REST API 发送回客户端。要使用 Nest 执行此操作,通常您需要执行以下操作:
@Controller("file")
export class FileController {
@Get()
getFile(@Res() res: Response) {
const file = createReadStream(join(process.cwd(), "package.json"));
file.pipe(res);
}
}
但这样做时,您最终会失去对后控制器拦截器逻辑的访问权限。为了处理这个问题,您可以返回一个 StreamableFile 实例,并且在幕后,框架将负责管道响应。
使用StreamableFile
类来处理流式文件
在 NestJS 中我们可以使用StreamableFile
来处理流式文件,要创建新的 StreamableFile,您可以将 Buffer 或 Stream 传递给 StreamableFile 构造函数。接来下我们事先一个接口把一个指定目录下的文件返回到浏览器端,具体的代码如下:
@Get('/model')
getFile(): StreamableFile {
const file = createReadStream(join(process.cwd(), '../../public/model.xlsx'));
return new StreamableFile(file);
}
StreamableFile
默认响应头部类型为application/octet-stream
,前端拿到这个流以后需要做特殊处理,如果您需要自定义响应,可以使用 res.set 方法或 @Header() 装饰器,如下所示:
@Get()
getFile(@Res({
passthrough: true }) res: Response): StreamableFile {
const file = createReadStream(join(process.cwd(), '../../public/model.xlsx'));
res.set({
'Content-Type': 'application/json',
'Content-Disposition': 'attachment; filename="model.xlsx"',
});
return new StreamableFile(file);
}
// Or even:
@Get()
@Header('Content-Type', 'application/json')
@Header('Content-Disposition', 'attachment; filename="model.xlsx"')
getStaticFile(): StreamableFile {
const file = createReadStream(join(process.cwd(), '../../public/model.xlsx'));
return new StreamableFile(file);
}