Skip to content

Upload files and perform validation in nestjs using decorators

License

Notifications You must be signed in to change notification settings

Jtplouffe/nestjs-file-upload

Repository files navigation

nestjs-file-upload

Upload files and perform validation in nestjs using decorators.

Table of content

Installation

Install using

npm i nestjs-file-upload

Usage

  1. Add the FileField decorator to the file fields in your dto.
import { Expose } from "class-transformer";
import { FileField, File } from "nestjs-file-upload";

export class MyDto {
    @Expose()
    @FileField()
    myFile: File;

    @Expose()
    anotherField: string;
}

The FileField decorator can be combined with other decorators, such as validation decorators from class-validator.

import { Expose } from "class-transformer";
import { FileField, File } from "nestjs-file-upload";

export class MyDto {
    @Expose()
    @FileField()
    @IsNotEmpty()
    myFile: File;
}
  1. Add the FileInjector decorator to the endpoint.
import { Body, Controller, Post, ValidationPipe } from "@nestjs/common";

@Controller("my-controller")
export class MyController {
    @Post()
    @FileInjector(MyDto)
    public uploadFile(@Dto(ValidationPipe) dto: MyDto): void {
        console.log("Received file", dto.myFile.filename);
    }
}

Arguments

An argument of type fileFieldOptions can be passed to the FileField decorator.

You can pass the following properties as options:

Argument Type Description
fieldname string Overrides the property key. Can be used if the field in the form has a different name.
allowedMimeTypes string[] Array of allowed mime types. Mime type validation is based on the reported type in the form. We may use magic numbers in the future.
maxSize number Maximum file size in bytes.
maxFile number Maximum number of files. If the number is 1, the property will have a value of File. If the value if greater than 1, the property will have a value of File[].

Example

An example is available in the example.

License

See the LICENSE for more info.

About

Upload files and perform validation in nestjs using decorators

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published