The Easiest Way to Upload Your Files to NestJS

Introduction

File Upload is very common in websites or applications. We upload images, videos, and documents almost every day.

On the internet, there are thousands of tutorials on how to implement File Upload in many languages and technologies. Today I will write a simple guide to demonstrate how to handle file upload in NestJS

Implementation

To handle file uploading, Nest provides a built-in module based on the Multer middleware package for Express. Multer handles data posted in the multipart/form-data format, which is primarily used for uploading files via an HTTP POST request. This module is fully configurable and you can adjust its behavior to your application requirements.

Warning: Multer cannot process data which is not in the supported multipart format (multipart/form-data).

For type safety, let’s install Multer typings package with:

yarn add @types/multer

To upload a single file, simply tie the FileInterceptor() interceptor to the route handler and extract file from the request using the @UploadedFile() decorator.

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}

The FileInterceptor() decorator takes two arguments:

  • fieldName: string that supplies the name of the field from the HTML form that holds a file
  • options: optional object of type MulterOptions.

Validation

To handle validation, we can use the UploadedFile() decorator with built-in validators:

@UploadedFile(
new ParseFilePipe({
validators: [
new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' }),
new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 4 }),
],
}),
)

I use 2 validators here

  • FileTypeValidator: we can pass a string or a regex. In this case, I specified only files with png jpeg and jpg extension
  • MaxFileSizeValidator: a number of bytes that we can limit, for instance, I set it to 4 megabytes

These validators are very naive, but it is simple enough for our app to work

Service

Although you can save the file directly to your database, I suggest you not to do that. Simply because It would be slow and hard for the front-end to read your file

In this example, I use a 3rd party image hosting service to upload my image there, then only save the url in the database

In this case, we can access the file very fast and use it in our app

const user = await this.userModel.findById(userId);
if (!user) {
throw 'User not found';
}
const formData = new FormData();
formData.append('image', avatar.buffer.toString('base64'));
const { data: imageData } = await firstValueFrom(
this.httpService
.post(
`https://api.imgbb.com/1/upload?expiration=600&key=${process.env.IMG_API_KEY}`,
formData,
)
.pipe(
catchError((error: AxiosError) => {
throw error;
}),
),
);
user.updateOne({ avatar: imageData.data.url }).exec();

Conclusion

With the example above, you will be able to understand and code your own file upload functionality in under 10 minutes.

I hope you can catch up with the article, if not, you can check out my full source code here


The Easiest Way to Upload Your Files to NestJS was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Kyle Le

Introduction

File Upload is very common in websites or applications. We upload images, videos, and documents almost every day.

On the internet, there are thousands of tutorials on how to implement File Upload in many languages and technologies. Today I will write a simple guide to demonstrate how to handle file upload in NestJS

Implementation

To handle file uploading, Nest provides a built-in module based on the Multer middleware package for Express. Multer handles data posted in the multipart/form-data format, which is primarily used for uploading files via an HTTP POST request. This module is fully configurable and you can adjust its behavior to your application requirements.

Warning: Multer cannot process data which is not in the supported multipart format (multipart/form-data).

For type safety, let’s install Multer typings package with:

yarn add @types/multer

To upload a single file, simply tie the FileInterceptor() interceptor to the route handler and extract file from the request using the @UploadedFile() decorator.

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}

The FileInterceptor() decorator takes two arguments:

  • fieldName: string that supplies the name of the field from the HTML form that holds a file
  • options: optional object of type MulterOptions.

Validation

To handle validation, we can use the UploadedFile() decorator with built-in validators:

@UploadedFile(
new ParseFilePipe({
validators: [
new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' }),
new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 4 }),
],
}),
)

I use 2 validators here

  • FileTypeValidator: we can pass a string or a regex. In this case, I specified only files with png jpeg and jpg extension
  • MaxFileSizeValidator: a number of bytes that we can limit, for instance, I set it to 4 megabytes

These validators are very naive, but it is simple enough for our app to work

Service

Although you can save the file directly to your database, I suggest you not to do that. Simply because It would be slow and hard for the front-end to read your file

In this example, I use a 3rd party image hosting service to upload my image there, then only save the url in the database

In this case, we can access the file very fast and use it in our app

const user = await this.userModel.findById(userId);
if (!user) {
throw 'User not found';
}
const formData = new FormData();
formData.append('image', avatar.buffer.toString('base64'));
const { data: imageData } = await firstValueFrom(
this.httpService
.post(
`https://api.imgbb.com/1/upload?expiration=600&key=${process.env.IMG_API_KEY}`,
formData,
)
.pipe(
catchError((error: AxiosError) => {
throw error;
}),
),
);
user.updateOne({ avatar: imageData.data.url }).exec();

Conclusion

With the example above, you will be able to understand and code your own file upload functionality in under 10 minutes.

I hope you can catch up with the article, if not, you can check out my full source code here


The Easiest Way to Upload Your Files to NestJS was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Kyle Le


Print Share Comment Cite Upload Translate Updates
APA

Kyle Le | Sciencx (2022-11-21T13:22:17+00:00) The Easiest Way to Upload Your Files to NestJS. Retrieved from https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/

MLA
" » The Easiest Way to Upload Your Files to NestJS." Kyle Le | Sciencx - Monday November 21, 2022, https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/
HARVARD
Kyle Le | Sciencx Monday November 21, 2022 » The Easiest Way to Upload Your Files to NestJS., viewed ,<https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/>
VANCOUVER
Kyle Le | Sciencx - » The Easiest Way to Upload Your Files to NestJS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/
CHICAGO
" » The Easiest Way to Upload Your Files to NestJS." Kyle Le | Sciencx - Accessed . https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/
IEEE
" » The Easiest Way to Upload Your Files to NestJS." Kyle Le | Sciencx [Online]. Available: https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/. [Accessed: ]
rf:citation
» The Easiest Way to Upload Your Files to NestJS | Kyle Le | Sciencx | https://www.scien.cx/2022/11/21/the-easiest-way-to-upload-your-files-to-nestjs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.