How to get file from external API in NestJS and then upload it to the AWS S3?
- User
How to get file from external API in NestJS and then upload it to the AWS S3?
- Assistant
To get a file from an external API and then upload it to AWS S3 in NestJS, you can follow these steps:
- Install required dependencies:
First, you need to install the required dependencies for making HTTP requests and working with AWS S3. You can install them using npm or yarn:
bashnpm install axios @nestjs/axios aws-sdk- Import required modules and services:
In your NestJS module, import the
HttpModuleandAWS S3services:typescript// app.module.ts import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; import { S3 } from 'aws-sdk'; import { AppController } from './app.controller'; import { AppService } from './app.service'; @Module({ imports: [HttpModule], controllers: [AppController], providers: [AppService, { provide: S3, useValue: new S3() }], }) export class AppModule {}- Create a service to handle the file download and upload:
Create a new service (e.g.,
FileService) to handle the file download and upload:typescript// file.service.ts import { HttpService } from '@nestjs/axios'; import { Injectable } from '@nestjs/common'; import { S3 } from 'aws-sdk'; import { lastValueFrom } from 'rxjs'; @Injectable() export class FileService { constructor( private httpService: HttpService, private s3: S3, ) {} async downloadAndUploadFile(externalUrl: string, s3Bucket: string, s3Key: string) { try { const response = await lastValueFrom(this.httpService.get(externalUrl, { responseType: 'arraybuffer' })); const params = { Bucket: s3Bucket, Key: s3Key, Body: response.data, ContentType: response.headers['content-type'], }; await this.s3.upload(params).promise(); return { message: 'File uploaded successfully' }; } catch (error) { throw new Error('Failed to download and upload the file'); } } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.