multer documentation code example

Example 1: express multer example

const multer = require('multer')
const { resolve } = require('path')
const { existsSync, unlink } = require('fs')

const diskStorage = multer.diskStorage({
	destination: (req, file, done) => {
		if (!file) return done(new Error('Upload file error'), null)

		const fileExits = existsSync(resolve(process.cwd(), `src/images/${file.originalname}`))
		if (!fileExits) return done(null, resolve(process.cwd(), 'src/images'))

		unlink(resolve(process.cwd(), `src/images/${file.originalname}`), (error) => {
			if (error) return done(error)
			return done(null, resolve(process.cwd(), 'src/images'))
		})
	},
	filename: (req, file, done) => {
		if (file) {
			const extFile = file.originalname.replace('.', '')
			const extPattern = /(jpg|jpeg|png|gif|svg)/gi.test(extFile)
			if (!extPattern) return done(new TypeError('File format is not valid'), null)
			req.photo = file.originalname
			return done(null, file.originalname)
		}
	}
})

const fileUpload = multer({ storage: diskStorage, limits: 1000000 })

module.exports = { fileUpload }

Example 2: multer()

var multer = require('multer');
var upload = multer({dest:'uploads/'});

Example 3: multer npm

$ npm install --save multer file upload node

Example 4: multer

var express = require('express')var multer  = require('multer')var upload = multer({ dest: 'uploads/' }) var app = express() app.post('/profile', upload.single('avatar'), function (req, res, next) {  // req.file is the `avatar` file  // req.body will hold the text fields, if there were any}) app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {  // req.files is array of `photos` files  // req.body will contain the text fields, if there were any}) var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])app.post('/cool-profile', cpUpload, function (req, res, next) {  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files  //  // e.g.  //  req.files['avatar'][0] -> File  //  req.files['gallery'] -> Array  //  // req.body will contain the text fields, if there were any})