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 { Controller, Get, Query,
Validating paginated queries in NestJS
pagination
validation
pipes
Intermediate
7 steps
python
import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker
Testing FastAPI routes with dependency overrides
testing
fixtures
dependency-injection
Intermediate
7 steps
typescript
import { AsyncLocalStorage } from 'node:async_hooks'; import { randomUUID } from 'node:crypto'; import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express';
Request correlation IDs in NestJS with AsyncLocalStorage
async-local-storage
middleware
logging
Advanced
8 steps
java
public record ServerConfig( String host, int port, Duration timeout,
Loading typed config into a Java record
records
factory-methods
parsing
Intermediate
7 steps
java
public final class IbanValidator { private static final Map<String, Integer> COUNTRY_LENGTHS = Map.ofEntries( Map.entry("DE", 22), Map.entry("FR", 27), Map.entry("GB", 22),
Validating IBANs with the mod-97 checksum
validation
checksum
modular-arithmetic
Intermediate
8 steps
typescript
@Component({ selector: 'app-article-editor', templateUrl: './article-editor.component.html', })
Autosaving a form with RxJS in Angular
reactive-forms
rxjs-operators
debouncing
Advanced
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.