Multer is a middleware for handling multipart/form data in Node.js applications, including NestJS. It is commonly used for handling file uploads. NestJS is a popular framework for building scalable and maintainable server-side applications with TypeScript.
To use Multer in a NestJS application, you can follow these steps:
Step 1: Install Multer as a dependency in NestJs:
yarn add -d @types/multer
Step 2: write a code
import { Controller, Get } from '@nestjs/common';
import {
Param,
Post,
Res,
UploadedFiles,
UseInterceptors,
} from '@nestjs/common/decorators';
import { FilesInterceptor } from '@nestjs/platform-express/multer';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Post()
@UseInterceptors(FilesInterceptor('image'))
uploadFile(@UploadedFiles() file) {
console.log(file);
}
@Get(':imgpath')
seeUploadFile(@Res() req, @Param('imgpath') image) {
return req.sendFile(image, { root: 'img' });
}
}
To upload multiple files in Multer in NestJs
@Post()
@UseInterceptors(
FileFieldsInterceptor([
{
name: 'profile',
maxCount: 2,
},
{
name: 'profile2',
maxCount: 1,
},
]),
)
uploadFiles(
@UploadedFiles()
file: {
profile?: Express.Multer.File[];
profile2?: Express.Multer.File[];
},
): object {
console.log(file);
return {
message: 'File Upload',
};
}
In this example, the @UseInterceptors()
decorator is used to specify the FileInterceptor from @nestjs/platform-express as an interceptor for the uploadFile() endpoint. The FileInterceptor intercepts the incoming request, processes the uploaded file using Multer, and passes it to the uploadFile() method as an Express.Multer.The file object contains information about the uploaded file such as its original name, mime type, size, and path on the server.