0
0
NestJSframework~5 mins

File validation pipe in NestJS

Choose your learning style9 modes available
Introduction

A file validation pipe checks uploaded files to make sure they are safe and correct before your app uses them.

When users upload images and you want to allow only certain types like PNG or JPG.
When you want to limit the file size to prevent very large uploads.
When you need to check the file format before saving it to your server.
When you want to reject files that do not meet your rules early in the request.
When you want to give clear error messages if the file is not valid.
Syntax
NestJS
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class FileValidationPipe implements PipeTransform {
  transform(file: any) {
    // validation logic here
    if (!file) {
      throw new BadRequestException('No file uploaded');
    }
    if (!['image/png', 'image/jpeg'].includes(file.mimetype)) {
      throw new BadRequestException('Invalid file type');
    }
    if (file.size > 1_000_000) { // 1MB limit
      throw new BadRequestException('File too large');
    }
    return file;
  }
}

The transform method runs automatically on the input before your controller gets it.

Throwing BadRequestException stops the request and sends an error to the user.

Examples
Simple check to make sure a file was uploaded.
NestJS
transform(file: any) {
  if (!file) {
    throw new BadRequestException('No file uploaded');
  }
  return file;
}
Check that the file is either PNG or JPEG.
NestJS
transform(file: any) {
  const allowedTypes = ['image/png', 'image/jpeg'];
  if (!allowedTypes.includes(file.mimetype)) {
    throw new BadRequestException('Invalid file type');
  }
  return file;
}
Limit file size to 2 megabytes.
NestJS
transform(file: any) {
  const maxSize = 2_000_000; // 2MB
  if (file.size > maxSize) {
    throw new BadRequestException('File too large');
  }
  return file;
}
Sample Program

This controller accepts a file upload at POST /upload. It uses the FileValidationPipe to check the file before saving. If the file is valid, it returns a success message with the file name.

NestJS
import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { FileValidationPipe } from './file-validation.pipe';

@Controller('upload')
export class UploadController {
  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile(new FileValidationPipe()) file: Express.Multer.File) {
    return { message: 'File uploaded successfully', filename: file.originalname };
  }
}
OutputSuccess
Important Notes

Make sure your file upload setup (like Multer) matches the pipe's expected file object.

Customize validation rules to fit your app's needs.

Use clear error messages to help users fix upload problems.

Summary

File validation pipes check uploaded files early to keep your app safe.

They can check file type, size, and presence.

Throwing exceptions stops bad files and sends helpful errors.