简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM