How to Handle File Upload in NestJS: Fix and Best Practices
@UseInterceptors(FileInterceptor('file')) decorator with Multer middleware. Define an endpoint with @Post() and access the uploaded file via @UploadedFile() in the controller method.Why This Happens
Developers often try to handle file uploads in NestJS without using the Multer middleware or the proper decorators. This causes errors because NestJS does not process multipart/form-data requests by default.
Here is an example of broken code that tries to accept a file upload but misses the interceptor:
import { Controller, Post, UploadedFile } from '@nestjs/common'; @Controller('upload') export class UploadController { @Post() uploadFile(@UploadedFile() file: Express.Multer.File) { console.log(file); return { message: 'File received' }; } }
The Fix
To fix this, use the @UseInterceptors(FileInterceptor('file')) decorator from @nestjs/platform-express. This sets up Multer to handle the multipart/form-data and extract the file. Also, ensure the client sends the file with the field name 'file'.
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.originalname); return { message: 'File uploaded successfully', filename: file.originalname }; } }
Prevention
Always use the FileInterceptor or AnyFilesInterceptor for file uploads in NestJS. Validate file types and sizes to avoid security risks. Use DTOs and pipes for validation when possible. Test uploads with tools like Postman or curl to ensure the field names match.
Keep Multer configuration centralized if you have multiple upload endpoints.
Related Errors
Common related errors include:
- File is undefined: Happens if the interceptor is missing or the client sends the wrong field name.
- Payload too large: Multer limits file size by default; increase limits in Multer options if needed.
- Unsupported file type: Use file filters in Multer to restrict allowed file types.