Get NestJS从GridFS返回一个fie
我正在尝试使用Nest控制器从GridFS返回一个文件。据我所知,nest不尊重我的自定义Get NestJS从GridFS返回一个fie,get,http-headers,zip,httpresponse,nestjs,Get,Http Headers,Zip,Httpresponse,Nestjs,我正在尝试使用Nest控制器从GridFS返回一个文件。据我所知,nest不尊重我的自定义内容类型标题,我将其设置为application/zip,因为我在返回时收到一个文本内容类型(请参见屏幕截图) 我的nest控制器看起来像这样 @Get(':owner/:name/v/:version/download') @Header('Content-Type', 'application/zip') async downloadByVersion(@Param('owner') ow
内容类型
标题,我将其设置为application/zip
,因为我在返回时收到一个文本内容类型(请参见屏幕截图)
我的nest控制器看起来像这样
@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);
}
@Get(':owner/:name/v/:version/download')
@标题('Content-Type','application/zip')
异步下载版本(@Param('owner')所有者:字符串,@Param('name')名称:字符串,@Param('version')版本:字符串,@Res()Res):承诺{
让bundleData=wait this.service.getSwimbundleByVersion(所有者、名称、版本);
让downloadFile=等待这个.service.downloadSwimbundle(bundleData['meta']['fileData']['u id']);
返回res.pipe(下载文件);
}
这是服务电话
downloadSwimbundle(fileId: string): Promise<GridFSBucketReadStream> {
return this.repository.getFile(fileId)
}
downloadSwimbundle(fileId:string):承诺{
返回此.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)
});
}
异步getFile(fileId:string):承诺{
const db=等待this.dbSource.db;
const bucket=new GridFSBucket(db,{bucketName:this.collectionName});
const downloadStream=bucket.openDownloadStream(新ObjectID(fileId));
返回新承诺(解决=>{
解析(下载流)
});
}
我的最终目标是调用
下载
端点,让浏览器注册它是一个zip文件并下载它,而不是在浏览器中看到二进制文件。我们将非常感谢您为实现这一目标所做的任何指导。感谢阅读您还需要使用文件名设置内容配置
标题。如果文件名始终相同,则可以使用@Header()
装饰器;如果需要根据控制器中的某些参数发回不同的文件名,则可以直接在响应对象上使用setHeader
以下两种示例控制器方法都用于将可下载文件从本地文件系统发送回浏览器
@Get('/test')
@标题('Content-Type','application/pdf')
@标题('Content-Disposition','attachment;filename=something.pdf')
getTest(@Res()响应:响应){
const data=createReadStream(path.join(uu dirname,'test.pdf');
数据管道(响应);
}
@获取('/test')
@标题('Content-Type','application/pdf')
getTest(@Res()响应:响应){
const data=createReadStream(path.join(uu dirname,'test.pdf');
response.setHeader(
“内容处置”,
'附件;文件名=另一个.pdf',
);
数据管道(响应);
}