从Nestjs的url下载图像

时间:2019-05-24 04:56:34

标签: nestjs

我想从电报帐户下载用户个人资料图片,并使用nestjs框架将其存储在本地存储中。

1 个答案:

答案 0 :(得分:1)

@Controller()
export class Controller {
    constructor(
        private readonly httpService: HttpService,
    ) {
    }

    @Get()
    async downloadImage(@Res() res) {
        const writer = fs.createWriteStream('./image.png');

        const response = await this.httpService.axiosRef({
            url: 'https://example.com/image.png',
            method: 'GET',
            responseType: 'stream',
        });

        response.data.pipe(writer);

        return new Promise((resolve, reject) => {
            writer.on('finish', resolve);
            writer.on('error', reject);
        });
    }
}