How to return an image file correctly using nest.js?

你说的曾经没有我的故事 提交于 2020-01-25 08:57:33

问题


I'm trying to return the requested image file. My client is downloading the file, but I can't display it because it's an invalid png file. If I open the stored file tmpFile.png, I can see it correctly. So probably the problem is on how I'm sending it back to the client asking for it.

// 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:


this should works:

// 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);
}


来源:https://stackoverflow.com/questions/53956655/how-to-return-an-image-file-correctly-using-nest-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!