NestJS File Upload Multiple File Type Verification
Simple solution for multiple file validation upon upload with NestJS
I had this problem limiting the types of files going to the backend using Nestjs.
So I built a custom validator, here's how it looks:
import {BadRequestException, Injectable, PipeTransform} from '@nestjs/common';
import {extname} from 'path';
export function getFileValidator(): PipeTransform {
return new ParseFilePipeDocument();
}
@Injectable()
export class ParseFilePipeDocument implements PipeTransform {
private readonly allowedExtensions = [ '.png', '.pdf', '.jpeg', '.jpg'];
transform(value: Express.Multer.File): Express.Multer.File {
const extension = extname(value.originalname);
if(!this.allowedExtensions.includes(extension)) {
throw new BadRequestException(`File type ${extension} not supported`);
}
return value;
}
}
And here's how I use it in my Controller
class:
@Controller("path-to-controller")
export class ExampleController {
constructor(
private readonly exampleService: ExampleService
) {}
@Post('documents/upload')
async createDocument(
@Body() createDocDto: CreateDocumentDTO,
@UploadedFile(getFileValidator()) document: Express.Multer.File
) {
return this.exampleService.uploadDocument(document);
}
}
Pretty neat hm?
Like what you see? Check out my projects and my youtube channel, or give me a thanks on Twitter.