Handling file uploads in web applications is a common requirement, and NestJS provides elegant solutions to implement it. With its modular architecture and decorators, NestJS makes it straightforward to manage file uploads, ensuring flexibility and maintainability. This guide will take you through the process of uploading and managing files in a NestJS application step by step.
First, let's get our NestJS environment set up if you haven't already. If you need to start a new project, you can do that with the following command:
npm i -g @nestjs/cli nest new nest-file-upload cd nest-file-upload
Then install the necessary packages for file uploads:
npm install @nestjs/platform-express multer
multipart/form-data
, which is primarily used for uploading files.NestJS allows you to use Multer directly via controllers. Here's how to create a basic file upload endpoint.
Create a new controller for handling file uploads:
nest generate controller upload
This will create an upload.controller.ts
file. Now, let's implement a simple file upload method.
import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; @Controller('upload') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file')) uploadFile(@UploadedFile() file: Express.Multer.File) { console.log(file); return { message: 'File uploaded successfully!', filePath: file.path, }; } }
@Controller('upload')
: This defines the base route for this controller.@Post()
: This decorator specifies that this method will handle HTTP POST requests.@UseInterceptors(FileInterceptor('file'))
: This utilizes Multer's FileInterceptor
to manage file uploads. The string 'file'
corresponds to the name attribute of the uploaded file in the form.@UploadedFile() file
: This decorator extracts the uploaded file from the request.Start your NestJS application:
npm run start
You can use tools like Postman or cURL to test your file upload. Set up a POST request to http://localhost:3000/upload
and choose a file to upload.
By default, Multer stores files in memory, which may not be ideal for larger files. You can configure Multer to store files on the server.
Add the following code to configure Multer to use disk storage:
import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { v4 as uuidv4 } from 'uuid'; import { extname } from 'path'; @Controller('upload') export class UploadController { @Post() @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: './uploads', filename: (req, file, callback) => { const uniqueSuffix = uuidv4() + extname(file.originalname); callback(null, `${file.fieldname}-${uniqueSuffix}`); }, }), })) uploadFile(@UploadedFile() file: Express.Multer.File) { return { message: 'File uploaded successfully!', filePath: file.path, }; } }
Make sure to create the uploads
directory in your project root so files can be stored correctly.
It’s important to validate uploaded files to enhance security and maintain integrity. You can use Multer's built-in file filter for this:
@UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: './uploads', filename: (req, file, callback) => { const uniqueSuffix = uuidv4() + extname(file.originalname); callback(null, `${file.fieldname}-${uniqueSuffix}`); }, }), fileFilter: (req, file, callback) => { if (!file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) { return callback(new Error('Only image files are allowed!'), false); } callback(null, true); }, }))
Now that we have the upload functionality, let's implement file downloads. Create the following route in your upload.controller.ts
.
import { Controller, Get, Res, Param } from '@nestjs/common'; import { Response } from 'express'; import { join } from 'path'; @Controller('upload') export class UploadController { // Other methods ... @Get(':filename') async downloadFile(@Param('filename') filename: string, @Res() res: Response) { const filePath = join(__dirname, '..', '..', 'uploads', filename); res.download(filePath); } }
In this comprehensive guide, you’ve learned how to implement file uploads and management using NestJS and Multer. From setting up routes, configuring storage options, validating files, to downloading them, each step builds upon the previous one, giving you a robust framework for file handling. With NestJS, you can create structured and efficient file management solutions tailored to your application's needs. Happy coding!
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS