How to Handle File Uploads in NestJS

Updated: January 1, 2024 By: Guest Contributor Post a comment

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.