NestJS从GridFS归来 [英] NestJS return a fie from GridFS
问题描述
我正在尝试使用Nest控制器从GridFS返回文件.据我所知,nest不遵守我设置为application/zip
的自定义content-type
标头,因为返回时我收到的是文本内容类型(请参见屏幕截图).
I am trying to return a file from GridFS using my Nest controller. As far as I can tell nest is not respecting my custom content-type
header which i set to application/zip
, as I am receiving a text content type upon return (see screenshot).
我的巢状控制器看起来像这样
My nest controller looks like this
@Get(':owner/:name/v/:version/download')
@Header('Content-Type', 'application/zip')
async downloadByVersion(@Param('owner') owner: string, @Param('name') name: string, @Param('version') version: string, @Res() res): Promise<any> {
let bundleData = await this.service.getSwimbundleByVersion(owner, name, version);
let downloadFile = await this.service.downloadSwimbundle(bundleData['meta']['fileData']['_id']);
return res.pipe(downloadFile);
}
这是服务电话
downloadSwimbundle(fileId: string): Promise<GridFSBucketReadStream> {
return this.repository.getFile(fileId)
}
从本质上讲是通行证.
async getFile(fileId: string): Promise<GridFSBucketReadStream> {
const db = await this.dbSource.db;
const bucket = new GridFSBucket(db, { bucketName: this.collectionName });
const downloadStream = bucket.openDownloadStream(new ObjectID(fileId));
return new Promise<GridFSBucketReadStream>(resolve => {
resolve(downloadStream)
});
}
我的最终目标是调用download
端点并让浏览器注册它是一个zip文件并下载它,而不是在浏览器中看到二进制文件.任何有关到达那里需要做什么的指导将不胜感激.感谢您的阅读
My end goal is to call the download
endpoint and have a browser register that it is a zip file and download it instead of seeing the binary in the browser. Any guidance on what needs to be done to get there would be greatly appreciated. Thanks for reading
推荐答案
您还需要使用文件名设置Content-Disposition
标头.如果文件名将始终相同,则可以使用@Header()
装饰器;如果需要能够根据控制器中的某些参数发送回不同的文件名,则可以直接在响应对象上使用setHeader
.
You also need to set the Content-Disposition
header with a file name. You can use the @Header()
decorator if the file name will always be the same or setHeader
directly on the response object if you need to be able to send back different file names based on some parameter in your controller.
以下两个示例控制器方法都可以从我的本地文件系统将可下载的文件发送回浏览器.
Both of the following example controller methods work for sending back a downloadable file to the browser from my local file system.
@Get('/test')
@Header('Content-Type', 'application/pdf')
@Header('Content-Disposition', 'attachment; filename=something.pdf')
getTest(@Res() response: Response) {
const data = createReadStream(path.join(__dirname, 'test.pdf'));
data.pipe(response);
}
@Get('/test')
@Header('Content-Type', 'application/pdf')
getTest(@Res() response: Response) {
const data = createReadStream(path.join(__dirname, 'test.pdf'));
response.setHeader(
'Content-Disposition',
'attachment; filename=another.pdf',
);
data.pipe(response);
}
这篇关于NestJS从GridFS归来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!