NestJS
File Upload
Handling single and multiple file uploads in NestJS using Multer.
File Upload Controller: Using FileInterceptor and FilesInterceptor to handle file uploads.
upload.controller.ts
typescript
import { Controller, Post, UseInterceptors, UploadedFile, UploadedFiles } from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { multerOptions } from './multer.config';
@Controller('upload')
export class UploadController {
@Post('single')
@UseInterceptors(FileInterceptor('file', multerOptions))
uploadSingleFile(@UploadedFile() file: Express.Multer.File) {
return {
message: 'File uploaded successfully',
file: file.filename,
path: file.path,
};
}
@Post('multiple')
@UseInterceptors(FilesInterceptor('files', 10, multerOptions))
uploadMultipleFiles(@UploadedFiles() files: Array<Express.Multer.File>) {
const uploadedFiles = files.map(file => ({
filename: file.filename,
path: file.path,
}));
return {
message: 'Files uploaded successfully',
files: uploadedFiles,
};
}
}
Multer Configuration: Setting up local storage options with destination and filename generation.
multer.config.ts
typescript
import { diskStorage } from 'multer';
import { extname } from 'path';
export const multerOptions = {
storage: diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
// Generate a unique filename using timestamp and a random string
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = extname(file.originalname);
cb(null, `${file.fieldname}-${uniqueSuffix}${ext}`);
},
}),
fileFilter: (req: any, file: any, cb: any) => {
// Only allow specific file types (e.g., images)
if (file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
cb(null, true);
} else {
cb(new Error('Unsupported file type'), false);
}
},
limits: {
fileSize: 5 * 1024 * 1024, // 5MB limit
},
};