Uploading Files to Amazon S3 Bucket in NestJs using File Buffer.
Amazon Simple Storage Service (S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. In this tutorial, we will learn how to use NestJS to upload files to an S3 bucket.
Prerequisites
- Node.js and npm installed on your machine
- An AWS account
- A Bucket created in your AWS S3
Setting up the project
Let’s start by creating a new NestJS project:
$ npm init nest-app file-upload-project
$ cd file-upload-project
Next, install the required dependencies:
$ npm install --save aws-sdk
$ npm install --save @nestjs/common @nestjs/core @nestjs/platform-express rxjs
Creating the S3 service
/** Uploading file to S3 and saving the file and file url in users document **/
async uploadFile(body: { file: Buffer, userId: string }) {
/** Generates a 4 digit random integer */
const generateRandomNumber = Math.floor(1000 + Math.random() * 9000);
const fileContent = Buffer.from(body.file.buffer);
/** Uploading the file to S3 Bucket */
const s3 = new AWS.S3();
const uploadResult = await s3.upload({
Bucket: process.env.AWS_BUCKET_NAME,
Body: fileContent,
Key: `${generateRandomNumber}-${body.userId['userId']}-${body.file['originalname']}`,
}).promise() /** It returns the file key (file name) and file location */
/** Updating the user document by id - setting s3 file url */
return this.userModel.findByIdAndUpdate(body.userId['userId'], {
fileUrl: uploadResult.Location,
})
}
In the code above, we are using the AWS SDK to create a new S3 client and define an upload
method that accepts a buffer, a bucket name, and a key (the file name). The method returns a promise that resolves to the URL of the uploaded file.
Don’t forget to replace your-access-key-id
and your-secret-access-key
with your own AWS credentials.
Creating the controller
Now let’s create a controller that will handle the file upload. In the src
directory, create a new file called upload.controller.ts
and add the following code:
@Post('upload/file')
@UseInterceptors(FileInterceptor('file'))
uploadFile(
@UploadedFile() file: any,
@Body() userId: string,
@Res() res: Response,
) {
/** Checking file size in bytes - if it's greater than 1MB then throws error */
if (file['size'] > 1000000) {
throw new NotAcceptableException; // throw error.
}
/** Checking file type - Here I'm allowing to upload CSV, XLS, XLSX*/
if (!((file['mimetype'] === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (file['mimetype'] === 'application/vnd.ms-excel') || (file['mimetype'] === 'text/csv'))) {
throw new NotAcceptableException; // throw error.
}
return this.service.uploadFile(file, userId);
}
Setup for Postman
- Select request method as POST
- Select Body and form-data
- And then select type as file
I hope this article will help you. If you love it please give it a like and share.