Search code examples
validationuploadnestjssizemulter

How to limit total size of uploaded files in NestJS using multer?


I am developing an app where user can upload multiple files which will then be added to an email as attachment. I can limit the file size of each file using multer options. However I cannot set a limit for the total number of fields.

What is the best practice for limiting the total size of files?

Here is how I parse incoming files:

@Post('send')
@UseInterceptors(
AnyFilesInterceptor({ limits: { fileSize: 2 \* 1024 \* 1024 } }),
)
sendEmailWithAttachment(
@Body() sendEmailPayload: SendEmailPayload,
@UploadedFiles() files: Array\<Express.Multer.File\>,
) {

I added 2mb limit for demonstration purposes.

I could write a function on the service level that checks the sum of the file sizes, but it did not seem very feasible.


Solution

  • You can use a Nest Guard to do this logic, for Example:

    @Injectable()
    export class FileSizeGuard implements CanActivate {
      constructor(private readonly maxTotalSize: number) {}
    
      canActivate(
        context: ExecutionContext,
      ): boolean | Promise<boolean> | Observable<boolean> {
        const request = context.switchToHttp().getRequest();
        const files: Express.Multer.File[] = request.files;
        const totalSize = files.reduce((acc, file) => acc + file.size, 0);
        if (totalSize > this.maxTotalSize) {
          return false;
        }
        return true;
      }
    }
    

    then use this guard above your controller endpoint:

    @Post('send')
    @UseGuards(new FileSizeGuard(10 * 1024 * 1024)) // limit total size to 10MB
    ...