Skip to content

Instantly share code, notes, and snippets.

@cdiaz
Last active February 9, 2022 04:19
Show Gist options
  • Save cdiaz/c6f9522d752a0cda04848450353518af to your computer and use it in GitHub Desktop.
Save cdiaz/c6f9522d752a0cda04848450353518af to your computer and use it in GitHub Desktop.
Upload files with Multer & NestJS
import { Middleware, NestMiddleware } from '@nestjs/common';
import { ExpressMiddleware } from '@nestjs/common/interfaces';
import * as multer from 'multer';
@Middleware(fields?)
export class MulterMiddleware implements NestMiddleware {
resolve() {
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, './public/images');
},
filename(req, file, cb) {
cb(null, file.originalname);
},
});
const fileFilter = (req, file, cb) => {
let extension = (file.originalname.split('.').pop())
//Put here your custom validation for file extensións.
// To accept the file pass `true`, like so:
cb(null, true)
// To reject this file pass `false` or throw Exception, like so:
//cb(new HttpException ("File format is not valid", HttpStatus.BAD_REQUEST), false)
}
return multer({
storage: storage,
limits: {
fileSize: 2097152//2 Megabytes
},
fileFilter: fileFilter
}).fields(fields)
}
}
import { Module, RequestMethod } from '@nestjs/common';
import { MiddlewaresConsumer, NestModule } from '@nestjs/common/interfaces';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MulterMiddleware } from './../common/middleware/multer.middleware';
@Module({
controllers: [..],
components: [..]
})
export class ProfileModule implements NestModule {
public configure(consumer: MiddlewaresConsumer) {
consumer
.apply(MulterMiddleware)
.with([{ name: 'picture' }])
.forRoutes(
{ path: '/profile', method: RequestMethod.POST },
{ path: '/profile/:id', method: RequestMethod.PUT }
);
}
}
@harshamv
Copy link

Any example of using this please?

@201RichK
Copy link

201RichK commented Feb 7, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment