Kind: Class
Source: packages/common/pipes/file/max-file-size.validator.ts
Part of: Common
Defines the built-in MaxSize File Validator
MaxFileSizeValidator is a built-in file validator that checks whether an uploaded file is smaller than a configured maximum size. It is typically used with NestJS ParseFilePipe to reject oversized uploads before they reach application logic.
Extends: FileValidator
Methods
| Method | Signature | Returns |
|---|---|---|
buildErrorMessage | buildErrorMessage(file: IFile) | string |
isValid | isValid(file: IFile) | boolean |
Where it refuses work
MaxFileSizeValidatorstops the work with an early return whenerrorMessage.MaxFileSizeValidatorstops the work with an early return whenmessage.MaxFileSizeValidatorstops the work with an early return whenfile?.size.MaxFileSizeValidatorstops the work with an early return when!this.validationOptions || !file.
Diagram
mermaidgraph LR A[Incoming uploaded file] --> B[ParseFilePipe] B --> C[MaxFileSizeValidator] C --> D{file.size < maxSize?} D -->|Yes| E[Continue request handling] D -->|No| F[buildErrorMessage()] F --> G[Return validation error]
Usage
tsimport {
Controller,
MaxFileSizeValidator,
ParseFilePipe,
Post,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
@Controller('uploads')
export class UploadController {
@Post()
@UseInterceptors(FileInterceptor('file'))
uploadFile(
@UploadedFile(
new ParseFilePipe({
validators: [
new MaxFileSizeValidator({
maxSize: 5 * 1024 * 1024, // 5 MB
}),
],
}),
)
file: Express.Multer.File,
) {
return {
filename: file.originalname,
size: file.size,
};
}
}
AI Coding Instructions
- Instantiate
MaxFileSizeValidatorwith amaxSizevalue in bytes; use clear constants for readable size limits. - Add the validator to
ParseFilePipealongside other validators such asFileTypeValidator. - Ensure the upload interceptor, such as
FileInterceptor, runs before attempting to validate the uploaded file. - Do not rely on client-provided file metadata alone; configure upload limits and storage settings as additional protection.
- Use
buildErrorMessage()behavior consistently when extending or composing file-validation error handling.
Was this page helpful?