Advertisement
aldikhan13

Nestjs Multer Custom File Upload

Mar 2nd, 2022 (edited)
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Example file upload using Multer in NodeJs using NestJs here
  2.  
  3.     @UseGuards(JsonWebToken.JwtAuthentication)
  4.     @Version('1')
  5.     @Post()
  6.     @UseInterceptors(
  7.         Multer.fields(
  8.             [
  9.                 { name: 'photo', maxCount: 1 },
  10.                 { name: 'document', maxCount: 1 }
  11.             ],
  12.             {
  13.                 storage: Multer.diskStorage,
  14.                 fileFilter: Multer.fileFilter
  15.             }
  16.         )
  17.     )
  18.     async fileUpload(
  19.         @Res() res: Response,
  20.         @Body() body: Record<string ,any>,
  21.         @UploadedFiles() files: { photo: Express.Multer.File[]; document: Express.Multer.File[] }
  22.     ): Promise<OutgoingMessage> {
  23.         try {
  24.             const serviceResponse: APIResponse = await this.service.fileUpload(body, files)
  25.             return res.status(serviceResponse.stat_code).json(serviceResponse)
  26.         } catch (e: any) {
  27.             return res.status(e.stat_code).json(e)
  28.         }
  29.     }
  30. }
  31.  
  32.  
  33. // Multer custom library here
  34.  
  35. import 'dotenv/config.js'
  36. import { MulterModule, FileFieldsInterceptor, FilesInterceptor, FileInterceptor } from '@nestjs/platform-express'
  37. import { mimeTypeSupport } from '@helpers/helper.mimeType'
  38. import aws from 'aws-sdk'
  39. import { Request } from 'express'
  40. import multer from 'multer'
  41. import multerS3 from 'multer-s3'
  42. import fs from 'fs'
  43.  
  44. aws.config.update({
  45.     accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  46.     secretAccessKey: process.env.AWS_ACCESS_KEY
  47. })
  48.  
  49. export class Multer {
  50.     static typeModule = MulterModule
  51.     static register = MulterModule.register
  52.     static fields = FileFieldsInterceptor
  53.     static array = FilesInterceptor
  54.     static single = FileInterceptor
  55.  
  56.     static diskStorage: multer.StorageEngine = multer.diskStorage({
  57.         destination(_: Request, file: Express.Multer.File, done: any) {
  58.             let linux: string = `${process.env.IMG_DIR}`
  59.             let window: string = process.env.TEMP || ''
  60.  
  61.             if (!file) {
  62.                 done(new Error('Uploading file failed'), null)
  63.             } else {
  64.                 if (process.platform === 'win32') {
  65.                     if (fs.existsSync(window)) {
  66.                         done(null, window)
  67.                     } else {
  68.                         done(new Error('No such file directory').message, null)
  69.                     }
  70.                 } else {
  71.                     if (fs.existsSync(linux)) {
  72.                         done(null, linux)
  73.                     } else {
  74.                         done(new Error('No such file directory').message, null)
  75.                     }
  76.                 }
  77.             }
  78.         },
  79.         filename(_req: Request, file: Express.Multer.File, done: any) {
  80.             if (!file) done(new Error('Get file upload failed'), null)
  81.             const fileName: string = `${Date.now().toString()} - ${file.originalname}`
  82.             done(null, fileName)
  83.         }
  84.     })
  85.  
  86.     static awsStorage: multer.StorageEngine = multerS3({
  87.         s3: new aws.S3(),
  88.         bucket: process.env.AWS_BUCKET_NAME,
  89.         contentType: multerS3.AUTO_CONTENT_TYPE,
  90.         serverSideEncryption: 'AES256',
  91.         metadata(_req: Request, file: Express.Multer.File, done: any) {
  92.             if (!file) done(new Error('Get file upload failed'), null)
  93.             const readFile: InstanceType<typeof stream.Readable> = new stream.Readable({
  94.                 read() {
  95.                     return true
  96.                 }
  97.             })
  98.             readFile
  99.                 .pipe(fs.createWriteStream(`${process.env.IMG_DIR}/${Date.now().toString()}-${file.originalname}`))
  100.                 .on('finish', Promise.resolve)
  101.                 .on('error', Promise.reject)
  102.  
  103.             done(null, file)
  104.         },
  105.         key(_req: Request, file: Express.Multer.File, done: any) {
  106.             done(null, `${Date.now().toString()}-${file.originalname}`)
  107.         }
  108.     })
  109.  
  110.     static fileFilter(_req: Request, file: Express.Multer.File, done: any) {
  111.         if (!mimeTypeSupport(file.mimetype)) throw new TypeError('mimetype not supported')
  112.         if (file.size >= 5242880) throw new TypeError('maximum file or image size must be 5 MB or under 5 MB')
  113.  
  114.         const fileName: string = `${Date.now().toString()} - ${file.originalname}`
  115.         done(null, fileName)
  116.     }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement