Sling Academy
Home/Node.js/How to Handle File Uploads in NestJS

How to Handle File Uploads in NestJS

Last updated: January 01, 2024

Introduction

Handling file uploads is a common requirement for many web applications. In this tutorial, we’ll explore how to manage file uploads in NestJS using TypeScript, ensuring best practices for scalability and maintainability.

Setting Up Your NestJS Project

Start by creating a new NestJS project if you haven’t already:

$ nest new project-name

Navigate into your project directory:

$ cd project-name

Installing Required Packages

First, install the necessary packages:

$ npm install @nestjs/platform-express multer

Basic File Upload

Set up a basic single file upload using Multer.

import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('upload')
export class UploadController {
    @Post()
    @UseInterceptors(FileInterceptor('file'))
    uploadFile(@UploadedFile() file) {
        console.log(file);
        return 'File uploaded successfully!';
    }
}

Ensure you configure your ‘main.ts’ to handle file uploads:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Multiple File Uploads

Next, let’s handle multiple file uploads:

import { Controller, Post, UseInterceptors, UploadedFiles } from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';

@Controller('uploads')
export class MultipleUploadController {
    @Post()
    @UseInterceptors(FilesInterceptor('files'))
    uploadMultiple(@UploadedFiles() files) {
        console.log(files);
        return 'Files uploaded successfully!';
    }
}

File Upload with Additional Data

Often, you’ll need to upload files alongside other form data:

import { Controller, Post, UseInterceptors, UploadedFile, Body } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('upload')
export class FileAndDataUploadController {
    @Post()
    @UseInterceptors(FileInterceptor('file'))
    uploadFileAndData(@UploadedFile() file, @Body() body) {
        console.log(file);
        console.log(body);
        return 'File and data uploaded successfully!';
    }
}

Advanced Configuration

Customize Multer options for better control over file uploads:

import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import * as multer from 'multer';

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, file.fieldname + '-' + uniqueSuffix)
    }
});

@Controller('upload')
export class CustomConfigUploadController {
    @Post()
    @UseInterceptors(FileInterceptor('file', { storage: storage }))
    uploadWithCustomConfig(@UploadedFile() file) {
        console.log(file);
        return 'File uploaded with custom configuration!';
    }
}

Handling File Upload Errors

Handle potential errors with an exception filter and custom logic:

import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { FileUploadException } from './file-upload.exception';

@Catch(FileUploadException)
export class FileUploadExceptionFilter implements ExceptionFilter {
  catch(exception: FileUploadException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(HttpStatus.BAD_REQUEST).json({
      statusCode: HttpStatus.BAD_REQUEST,
      message: 'Error uploading file',
      error: exception.message,
    });
  }
}

Conclusion

In this tutorial, we’ve covered how to handle file uploads in NestJS using Multer with various scenarios. Remember to handle file storage and security appropriately to safeguard your user’s data. Apply these techniques to enable robust file management features in your applications.

Next Article: How to Create Custom Decorators in NestJS

Previous Article: How to Use Interceptors and Guards in NestJS

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates