0
0
NestjsDebug / FixBeginner · 4 min read

How to Handle File Upload in NestJS: Fix and Best Practices

In NestJS, handle file uploads by using the @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:

typescript
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' };
  }
}
Output
Error: Cannot read property 'buffer' of undefined or file is undefined
🔧

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'.

typescript
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 };
  }
}
Output
{"message":"File uploaded successfully","filename":"example.png"}
🛡️

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.

Key Takeaways

Use @UseInterceptors(FileInterceptor('file')) to enable file upload handling in NestJS.
Access the uploaded file with @UploadedFile() in your controller method.
Ensure the client sends the file with the correct field name matching the interceptor.
Validate file size and type to prevent security issues.
Test file uploads with tools like Postman to confirm correct behavior.