Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

multer nestjs

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)
			done(null, file)
		},
		key(_req: Request, file: Express.Multer.File, done: any) {
			done(null, Date.now().toString())
		}
	})

	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)
	}
}
Comment

nestjs multer

// use like this
	// @Role('customers')
	@UseGuards(JsonWebToken.JwtAuthentication)
	@Version('1')
	@Post(':action')
	@UseInterceptors(
		Multer.fields(
			[
				{ name: 'ktp_photo', maxCount: 1 },
				{ name: 'selfie_photo', maxCount: 1 }
			],
			{
				storage: Multer.diskStorage,
				fileFilter: Multer.fileFilter
			}
		)
	)
	async signatureHandlers(
		@Res() res: Response,
		@Req() req: Request,
		@Body() body: any,
		@UploadedFiles() files: { ktp_photo: Express.Multer.File[]; selfie_photo: Express.Multer.File[]; document?: Express.Multer.File[] }
	): Promise<OutgoingMessage> {
		try {
			const serviceResponse: APIResponse = await this.service.signatureHandlers(body, files)
			return res.status(serviceResponse.stat_code).json(serviceResponse)
		} catch (e: any) {
			return res.status(e.stat_code).json(e)
		}
	}
}


// custom libs multer
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',
		key(_req: Request, file: Express.Multer.File, done: any) {
			const fileName: string = `${Date.now().toString()} - ${file.originalname}`
			done(null, fileName)
		}
	})

	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)
	}
}
Comment

PREVIOUS NEXT
Code Example
Typescript :: typescript default value if null 
Typescript :: golang check array index exists in slice 
Typescript :: how to compare two date in typescript 
Typescript :: using typescript with vue 
Typescript :: how to read excel spreadsheets in c++ 
Typescript :: Interface with custom property name types 
Typescript :: TypeScript Example Code Snippet 
Typescript :: fit_transform() takes 2 positional arguments but 3 were given 
Typescript :: htmlspecialchars() expects parameter 1 to be string array given in laravel blade 
Typescript :: conditional type typescript 
Typescript :: ts factory pattern 
Typescript :: delete array typescript 
Typescript :: paths typescript 
Typescript :: nestjs graphql schema description 
Typescript :: window object 
Typescript :: slice string into segments of 2 characters 
Typescript :: not working npx react-native init MyApp --template react-native-template-typescript 
Typescript :: how to set value to readonly property in typescript 
Typescript :: package minted missing pygments output 
Typescript :: coding and testing is done in following manner 
Typescript :: feature counts bioconda 
Typescript :: Carbohydrates and fats both 
Typescript :: how to find the total of the products added to the shopping cart in java program 
Typescript :: terrform variable list type 
Typescript :: find unique elements in pandas and their connection with other column 
Typescript :: ____________ determines the time spent in various parts of the unit. 
Typescript :: typescript programmatically union 
Typescript :: is there somone controlling the puppets in peppermint park 
Typescript :: check if an element exists laravel 
Typescript :: React Draft Wysiwyg typescript 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =