扫码一下
查看教程更方便
注意
本章介绍如何从 http 应用程序流式传输文件。 下面给出的示例不适用于 graphql 或微服务应用程序。
有时我们可能希望将文件从 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
是一个保存要返回的流的类。 要创建新的 streamablefile
,我们可以将 buffer 或 stream 传递给 streamablefile 构造函数。
streamablefile 类可以从@nestjs/common
导入。
默认情况下,fastify 可以支持发送文件,无需调用 stream.pipe(res)
,所以你根本不需要使用 streamablefile
类。 但是,nest 支持在这两种平台类型中使用 streamablefile
,因此如果我们最终在 express 和 fastify 之间切换,则无需担心两种引擎之间的兼容性。
可以在下面找到一个将 package.json 作为文件而不是 json 返回的简单示例,但这个想法自然地扩展到图像、文档和任何其他文件类型。
import { controller, get, streamablefile } from '@nestjs/common';
import { createreadstream } from 'fs';
import { join } from 'path';
@controller('file')
export class filecontroller {
@get()
getfile(): streamablefile {
const file = createreadstream(join(process.cwd(), 'package.json'));
return new streamablefile(file);
}
}
默认内容类型是 application/octet-stream
,如果需要自定义响应可以使用 res.set
方法。
import { controller, get, streamablefile, response } from '@nestjs/common';
import { createreadstream } from 'fs';
import { join } from 'path';
@controller('file')
export class filecontroller {
@get()
getfile(@response({ passthrough: true }) res): streamablefile {
const file = createreadstream(join(process.cwd(), 'package.json'));
res.set({
'content-type': 'application/json',
'content-disposition': 'attachment; filename="package.json"',
});
return new streamablefile(file);
}
}