NestJS File Upload Multiple File Type Verification

Photo by Oskar Yildiz / Unsplash

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?

Originally published at https://lucas-schiavini.com on March 8, 2023.

--

--