typescript 45 lines · 7 steps

Handling avatar uploads in NestJS

A NestJS controller that accepts an image upload, stores it safely on disk, and validates it before handing off to a service.

Explained by highlit
1import {
2 Controller,
3 Post,
4 UploadedFile,
5 UseInterceptors,
6 ParseFilePipeBuilder,
7 HttpStatus,
8} from '@nestjs/common';
9import { FileInterceptor } from '@nestjs/platform-express';
10import { diskStorage } from 'multer';
11import { extname } from 'path';
12import { randomUUID } from 'crypto';
13import { AvatarService } from './avatar.service';
14 
15@Controller('users/:id/avatar')
16export class AvatarController {
17 constructor(private readonly avatarService: AvatarService) {}
18 
19 @Post()
20 @UseInterceptors(
21 FileInterceptor('avatar', {
22 storage: diskStorage({
23 destination: './uploads/avatars',
24 filename: (_req, file, cb) => {
25 cb(null, `${randomUUID()}${extname(file.originalname)}`);
26 },
27 }),
28 limits: { fileSize: 2 * 1024 * 1024 },
29 }),
30 )
31 async upload(
32 @UploadedFile(
33 new ParseFilePipeBuilder()
34 .addFileTypeValidator({ fileType: /^image\/(jpeg|png|webp)$/ })
35 .addMaxSizeValidator({ maxSize: 2 * 1024 * 1024 })
36 .build({
37 errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
38 fileIsRequired: true,
39 }),
40 )
41 file: Express.Multer.File,
42 ) {
43 return this.avatarService.saveAvatar(file);
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Generating random filenames with the original extension prevents collisions and path-injection from user-supplied names.
  2. 2Multer limits guard resources at intake while ParseFilePipe validators enforce type and size at the handler boundary.
  3. 3Keeping controllers thin — validate and delegate — leaves persistence logic to an injected service.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Handling avatar uploads in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code