如何使用nest.js正确返回图像文件? [英] How to return an image file correctly using nest.js?
本文介绍了如何使用nest.js正确返回图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试返回所请求的图像文件.我的客户端正在下载文件,但由于它是无效的png
文件,所以无法显示.如果打开存储的文件tmpFile.png
,则可以正确看到它.因此,问题可能出在我如何将其发送回要求它的客户端上.
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 is my controller
async getFile(@Param('bucketname') bucketName: string, @Param('filename') fileName: string, @Res() response) {
return (await this.appService.getFile(bucketName, fileName)).pipe(response);
}
这篇关于如何使用nest.js正确返回图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文