How do you implement file uploads in NestJS?
Answer
NestJS integrates Multer via the @nestjs/platform-express package for file uploads. Use the FileInterceptor or FilesInterceptor with the @UploadedFile() decorator: @Post('upload') @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: './uploads', filename: (req, file, cb) => cb(null, uuid() + path.extname(file.originalname)) }), fileFilter: imageFileFilter, limits: { fileSize: 5 * 1024 * 1024 } })) uploadFile(@UploadedFile() file: Express.Multer.File) { return { url: \`/uploads/\${file.filename}\` }; }. Validate the file type in the fileFilter. For cloud storage, use multer-s3 or multer-gcs storage engines. Apply ParseFilePipe with built-in validators for type and size validation.
Previous
What is the @Global() decorator in NestJS?
Next
What is the CQRS pattern and how does NestJS support it?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?