nestjs res 下载zip文件 设置流传输 请求头设置
时间: 2024-04-15 22:30:36 浏览: 22
要设置响应头来传输ZIP文件,您可以使用`res.set()`方法来设置特定的头部字段。以下是一个示例:
```typescript
import { Controller, Get, Res } from '@nestjs/common';
import { createReadStream } from 'fs';
import { join } from 'path';
@Controller()
export class DownloadController {
@Get('/download')
downloadFile(@Res() res) {
const file = join(__dirname, 'path/to/your/file.zip');
const stream = createReadStream(file);
res.set({
'Content-Type': 'application/zip',
'Content-Disposition': 'attachment; filename=file.zip',
});
stream.pipe(res);
}
}
```
在上面的示例中,我们创建了一个读取文件的可读流,并使用`pipe()`方法将流传输到响应对象`res`中。在设置响应头之前,我们使用`res.set()`方法设置了两个头部字段:`Content-Type`和`Content-Disposition`。
`Content-Type`头部字段指定了响应的内容类型为ZIP文件('application/zip')。
`Content-Disposition`头部字段指定了浏览器如何处理响应。在这个例子中,我们设置为`attachment; filename=file.zip`,这将提示浏览器以附件形式下载文件,并将文件命名为`file.zip`。
请注意,这只是一个基本示例,您可能需要根据您的具体需求进行适当的调整和错误处理。