如何使用nest.js正确返回图像文件?

时间:2018-12-28 09:59:52

标签: javascript rest nestjs

我正在尝试返回所请求的图像文件。我的客户正在下载文件,但由于它是无效的png文件,所以无法显示。如果打开存储的文件tmpFile.png,则可以正确看到它。因此,问题可能出在我如何将其发送回要求它的客户端上。

// This is my controller
async getFile(@Param('bucketname') bucketName: string,
            @Param('filename') fileName: string) {
return await this.appService.getFile(bucketName, fileName);


// This is the function called
getFile(bucketName: string, fileName: string) {
    return new Promise(resolve => {
      this.minioClient.getObject(bucketName, fileName, (e, dataStream) => {
        if (e) {
          console.log(e);
        }

        let size = 0;
        const binary = fs.createWriteStream('tmpFile.png');

        dataStream.on('data', chunk => {
          size += chunk.length;
          binary.write(chunk);
        });
        dataStream.on('end', () => {
          binary.end();
          resolve(binary);
        });
      });
    });
  }

1 个答案:

答案 0 :(得分:1)

这应该有效:

// This is my controller
async getFile(@Param('bucketname') bucketName: string, @Param('filename') fileName: string, @Res() response) {
  return (await this.appService.getFile(bucketName, fileName)).pipe(response);
}