Last active
February 9, 2022 04:19
-
-
Save cdiaz/c6f9522d752a0cda04848450353518af to your computer and use it in GitHub Desktop.
Upload files with Multer & NestJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any example of using this please?