Upload files and perform validation in nestjs using decorators.
Install using
npm i nestjs-file-upload
- 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;
}
- 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);
}
}
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[] . |
An example is available in the example.
See the LICENSE for more info.