npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

nestjs-formdata-interceptor

v1.5.0

Published

nest js formdata interceptor

Readme

nestjs-formdata-interceptor

nestjs-formdata-interceptor is a powerful library for NestJS that provides seamless interception and handling of multipart/form-data requests. This functionality is particularly beneficial for efficiently managing file uploads in your application.

Getting Started

Installation

To install nestjs-formdata-interceptor using npm:

npm install nestjs-formdata-interceptor

OR using yarn

yarn add nestjs-formdata-interceptor

Usage

To use nestjs-formdata-interceptor, import it into the main directory of your NestJS application and configure it as shown below:

import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import { AppModule } from "./app.module";
import {
  FormdataInterceptor,
  LocalFileSaver,
} from "nestjs-formdata-interceptor";

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useGlobalInterceptors(
    new FormdataInterceptor({
      customFileName(context, originalFileName) {
        return `${Date.now()}-${originalFileName}`;
      },
      fileSaver: new LocalFileSaver({
        prefixDirectory: "./public",
        customDirectory(context, originalDirectory) {
          return originalDirectory;
        },
      }),
    }),
  );

  await app.listen(3000);
}
bootstrap();

Fastify

need to install @fastify/multipart package.

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import {
  FastifyAdapter,
  NestFastifyApplication,
} from "@nestjs/platform-fastify";
import fastifyMultipart from "@fastify/multipart";
import {
  LocalFileSaver,
  FormdataInterceptor,
} from "nestjs-formdata-interceptor";

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app.register(fastifyMultipart);

  app.useGlobalInterceptors(
    new FormdataInterceptor({
      customFileName(context, originalFileName) {
        return `${Date.now()}-${originalFileName}`;
      },
      fileSaver: new LocalFileSaver({
        prefixDirectory: "./public",
        customDirectory(context, originalDirectory) {
          return originalDirectory;
        },
      }),
    }),
  );

  await app.listen(3000);
}
bootstrap();

OR

you can use route spesific interceptor

import { Body, Controller, Post, UseInterceptors } from "@nestjs/common";
import { AppService } from "./app.service";
import { CreateDto } from "./dto/create.dto";
import { FormdataInterceptor } from "nestjs-formdata-interceptor";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post()
  @UseInterceptors(new FormdataInterceptor())
  getHello(@Body() createDto: CreateDto) {
    // your controller logic
  }
}

Explanation

1. Custom File Name:

The customFileName function allows you to generate custom file names for each uploaded file. In the example above, the file name is prefixed with the current timestamp followed by the original file name.

2. File Saver:

  • The LocalFileSaver is used to define the directory where the files will be saved.

    • prefixDirectory specifies the root directory where all files will be saved.
    • customDirectory allows you to specify a custom sub-directory within the root directory. By default, it uses the original directory provided.

Custom File Saver

If you need custom file-saving logic, implement the IFileSaver interface. Here's an example:

import { FileData, IFileSaver } from "nestjs-formdata-interceptor";
import { ExecutionContext } from "@nestjs/common";

export class CustomFileSaver implements IFileSaver {
  public save(
    fileData: FileData,
    context: ExecutionContext,
    args: unknown, // this will be get from save method payload
  ): any {
    // do your file save logic
    // and return the file save data
  }

  public saveMany(
    fileData: FileData[],
    context: ExecutionContext,
    args?: unknown,
  ): any {
    // to your bulk save logic
    // and return the file save data
  }
}

Then, use your custom file saver in the interceptor configuration:

import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import { AppModule } from "./app.module";
import { FormdataInterceptor } from "nestjs-formdata-interceptor";
import { CustomFileSaver } from "path-to-your-file-saver";

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useGlobalInterceptors(
    new FormdataInterceptor({
      customFileName(context, originalFileName) {
        return `${Date.now()}-${originalFileName}`;
      },
      fileSaver: new CustomFileSaver(),
    }),
  );

  await app.listen(3000);
}
bootstrap();

File Validation

If you are using class-validator describe dto and specify validation rules

import { IsArray, IsNotEmpty } from "class-validator";
import {
  FileData,
  LocalFileData,
  HasMimeType,
  IsFileData,
  MaxFileSize,
  MimeType,
  MinFileSize,
  MultipleFileData,
} from "nestjs-formdata-interceptor";

export class CreateDto {
  @IsFileData()
  @IsNotEmpty()
  @HasMimeType([MimeType["video/mp4"], "image/png"])
  @MinFileSize(2000000)
  @MaxFileSize(4000000)
  // single file
  file: LocalFileData;

  @IsArray()
  @IsNotEmpty()
  @IsFileData({ each: true })
  @HasMimeType([MimeType["video/mp4"], "image/png"], { each: true })
  @MinFileSize(2000000, { each: true })
  @MaxFileSize(4000000, { each: true })
  // array file
  // or you can use LocalFileData[] but it will lose bulkSave method
  // this this type is extend from Array class so you can still use array build in method like map, filter, ..etc.
  files: MultipleFileData<Promise<string>, string>;

  @IsFileData()
  @IsNotEmpty()
  @HasMimeType([MimeType["video/mp4"], "image/png"])
  @MinFileSize(2000000)
  @MaxFileSize(4000000)
  /**
   * customize file data save method
   * @param args [string] the payload sent to the custom file saver
   * @returns [Promise<string>] the file path where the file was saved
   * */
  customizeFileData: FileData<Promise<string>, string>;
}

Controller

Define your controller to handle file uploads:

import { Body, Controller, Post } from "@nestjs/common";
import { AppService } from "./app.service";
import { CreateDto } from "./dto/create.dto";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post()
  async getHello(@Body() createDto: CreateDto) {
    // save single file
    createDto.file.save(); // by default the file save data type is string

    // custom the file path on save function
    createDto.file.save({ path: "/custom-path" }); // This path will be appended to the prefix directory if it is set.

    // save multiple file if you using LocalFileData[]
    createDto.files.map((file) => file.save()); // by default the file save data type is string

    // save multiple file if you using MultipleFileData
    createDto.files.bulkSave();

    // customize file data example
    await createDto.customizeFileData.save("bucket_name"); // it will be returning Promise<string>
  }
}

With this setup, nestjs-formdata-interceptor will manage multipart/form-data requests efficiently, allowing for structured handling of file uploads in your NestJS application.

Contributors

License

MIT