A file validation pipe checks uploaded files to make sure they are safe and correct before your app uses them.
File validation pipe in 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.
transform(file: any) {
if (!file) {
throw new BadRequestException('No file uploaded');
}
return file;
}transform(file: any) {
const allowedTypes = ['image/png', 'image/jpeg'];
if (!allowedTypes.includes(file.mimetype)) {
throw new BadRequestException('Invalid file type');
}
return file;
}transform(file: any) {
const maxSize = 2_000_000; // 2MB
if (file.size > maxSize) {
throw new BadRequestException('File too large');
}
return file;
}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.
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 }; } }
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.
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.
Practice
FileValidationPipe in NestJS?Solution
Step 1: Understand the role of validation pipes in NestJS
Validation pipes are used to check and validate incoming data before it reaches the controller logic.Step 2: Apply this to file uploads
AFileValidationPipespecifically checks uploaded files for correct type, size, and presence to prevent bad data.Final Answer:
To check uploaded files for type, size, and presence before processing -> Option CQuick Check:
File validation = check file properties [OK]
- Thinking pipes upload or transform files
- Confusing validation with file storage
- Assuming pipes compress files automatically
Solution
Step 1: Identify the correct decorator for validation pipes
In NestJS, validation pipes are applied using the@UsePipes()decorator.Step 2: Match the usage with file upload
TheFileValidationPipeis a pipe, so it must be passed inside@UsePipes()to validate the uploaded file.Final Answer:
@UsePipes(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {} -> Option AQuick Check:
Validation pipe = @UsePipes() [OK]
- Using @UseGuards or @UseFilters instead of @UsePipes
- Applying pipes without instantiating them
- Confusing interceptors with pipes
export class FileValidationPipe implements PipeTransform {
transform(file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is required');
if (file.size > 1_000_000) throw new BadRequestException('File too large');
return file;
}
}Solution
Step 1: Analyze the size check in the transform method
The pipe checks iffile.sizeis greater than 1,000,000 bytes (1MB).Step 2: Understand the exception thrown on size violation
If the file is too large, it throwsBadRequestException('File too large'), stopping the request.Final Answer:
The pipe throws a BadRequestException with message 'File too large' -> Option DQuick Check:
File size > 1MB = BadRequestException [OK]
- Assuming the pipe accepts large files
- Confusing BadRequestException with NotFoundException
- Ignoring the file presence check
export class FileValidationPipe implements PipeTransform {
transform(file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is required');
if (file.mimetype !== 'image/png' || file.mimetype !== 'image/jpeg') {
throw new BadRequestException('Invalid file type');
}
return file;
}
}Solution
Step 1: Examine the mimetype condition
The condition uses||(OR) between two checks:file.mimetype !== 'image/png'ORfile.mimetype !== 'image/jpeg'.Step 2: Understand why this always triggers
Because a file cannot be both 'image/png' and 'image/jpeg' at the same time, one of these will always be true, causing the exception every time.Final Answer:
The mimetype check always throws because of incorrect logical operator -> Option AQuick Check:
Use AND (&&) to check mimetype correctly [OK]
- Using || instead of && in mimetype checks
- Forgetting to return the file after validation
- Throwing wrong exception types
Solution
Step 1: Verify correct logic for presence and mimetype
Checkif (!file)throw, thenif (file.mimetype !== 'application/pdf')throw 'Only PDFs allowed'. Uses!==to reject non-PDFs.Step 2: Separate size check for smaller than 2MB
if (file.size >= 2_000_000)throw 'File too large'. Uses>=to reject 2MB or larger.Step 3: Eliminate distractors
B throws if PDF; C's&&accepts non-PDF if small; D's>accepts exactly 2MB.Final Answer:
export class PdfValidationPipe implements PipeTransform { transform(file: Express.Multer.File) { if (!file) throw new BadRequestException('File is required'); if (file.mimetype !== 'application/pdf') throw new BadRequestException('Only PDFs allowed'); if (file.size >= 2_000_000) throw new BadRequestException('File too large'); return file; } } -> Option BQuick Check:
!== mimetype, >= size, separate ifs [OK]
- Using === instead of !== for mimetype check
- Combining conditions incorrectly with && or ||
- Not throwing specific error messages
Ready to prove it?
Pass the test and this pattern moves unknown
