multer express example

Example 1: how to set file type and size in multer

var multer = require('multer')
var upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})

Example 2: express multer

$ npm install --save multer

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

Example 3: express multer example

const multer = require('multer')
const { extname, resolve } = require('path')

const diskStorage = multer.diskStorage({
	destination: (req, file, done) => {
		if (!file) return done(new Error('Upload file error'), null)
		return done(null, resolve(process.cwd(), 'src/images'))
	},
	filename: (req, file, done) => {
		if (file) {
			const imagePattern = /(jpg|jpeg|png|gif|svg)/gi
			const mathExt = extname(file.originalname).replace('.', '')

			if (!imagePattern.test(mathExt)) {
				return new TypeError('File format is not valid')
			}

			req.file = file.originalname
			return done(null, file.originalname)
		}
	}
})

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

module.exports = { fileUpload }