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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Generating random filenames with the original extension prevents collisions and path-injection from user-supplied names.
- 2Multer limits guard resources at intake while ParseFilePipe validators enforce type and size at the handler boundary.
- 3Keeping controllers thin — validate and delegate — leaves persistence logic to an injected service.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/handling-avatar-uploads-in-nestjs-explained-typescript-b25f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.