Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example file upload using Multer in NodeJs using NestJs here
- @UseGuards(JsonWebToken.JwtAuthentication)
- @Version('1')
- @Post()
- @UseInterceptors(
- Multer.fields(
- [
- { name: 'photo', maxCount: 1 },
- { name: 'document', maxCount: 1 }
- ],
- {
- storage: Multer.diskStorage,
- fileFilter: Multer.fileFilter
- }
- )
- )
- async fileUpload(
- @Res() res: Response,
- @Body() body: Record<string ,any>,
- @UploadedFiles() files: { photo: Express.Multer.File[]; document: Express.Multer.File[] }
- ): Promise<OutgoingMessage> {
- try {
- const serviceResponse: APIResponse = await this.service.fileUpload(body, files)
- return res.status(serviceResponse.stat_code).json(serviceResponse)
- } catch (e: any) {
- return res.status(e.stat_code).json(e)
- }
- }
- }
- // Multer custom library here
- import 'dotenv/config.js'
- import { MulterModule, FileFieldsInterceptor, FilesInterceptor, FileInterceptor } from '@nestjs/platform-express'
- import { mimeTypeSupport } from '@helpers/helper.mimeType'
- import aws from 'aws-sdk'
- import { Request } from 'express'
- import multer from 'multer'
- import multerS3 from 'multer-s3'
- import fs from 'fs'
- aws.config.update({
- accessKeyId: process.env.AWS_ACCESS_KEY_ID,
- secretAccessKey: process.env.AWS_ACCESS_KEY
- })
- export class Multer {
- static typeModule = MulterModule
- static register = MulterModule.register
- static fields = FileFieldsInterceptor
- static array = FilesInterceptor
- static single = FileInterceptor
- static diskStorage: multer.StorageEngine = multer.diskStorage({
- destination(_: Request, file: Express.Multer.File, done: any) {
- let linux: string = `${process.env.IMG_DIR}`
- let window: string = process.env.TEMP || ''
- if (!file) {
- done(new Error('Uploading file failed'), null)
- } else {
- if (process.platform === 'win32') {
- if (fs.existsSync(window)) {
- done(null, window)
- } else {
- done(new Error('No such file directory').message, null)
- }
- } else {
- if (fs.existsSync(linux)) {
- done(null, linux)
- } else {
- done(new Error('No such file directory').message, null)
- }
- }
- }
- },
- filename(_req: Request, file: Express.Multer.File, done: any) {
- if (!file) done(new Error('Get file upload failed'), null)
- const fileName: string = `${Date.now().toString()} - ${file.originalname}`
- done(null, fileName)
- }
- })
- static awsStorage: multer.StorageEngine = multerS3({
- s3: new aws.S3(),
- bucket: process.env.AWS_BUCKET_NAME,
- contentType: multerS3.AUTO_CONTENT_TYPE,
- serverSideEncryption: 'AES256',
- metadata(_req: Request, file: Express.Multer.File, done: any) {
- if (!file) done(new Error('Get file upload failed'), null)
- const readFile: InstanceType<typeof stream.Readable> = new stream.Readable({
- read() {
- return true
- }
- })
- readFile
- .pipe(fs.createWriteStream(`${process.env.IMG_DIR}/${Date.now().toString()}-${file.originalname}`))
- .on('finish', Promise.resolve)
- .on('error', Promise.reject)
- done(null, file)
- },
- key(_req: Request, file: Express.Multer.File, done: any) {
- done(null, `${Date.now().toString()}-${file.originalname}`)
- }
- })
- static fileFilter(_req: Request, file: Express.Multer.File, done: any) {
- if (!mimeTypeSupport(file.mimetype)) throw new TypeError('mimetype not supported')
- if (file.size >= 5242880) throw new TypeError('maximum file or image size must be 5 MB or under 5 MB')
- const fileName: string = `${Date.now().toString()} - ${file.originalname}`
- done(null, fileName)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement