Metuuu
10/5/2018 - 10:46 AM

Multer upload images (NodeJS Express)

import express from 'express';
import bodyParser from 'body-parser';
import multer from 'multer';


const port = process.env.PORT || 80
const app = express()

app.use(bodyParser.json()) //{ limit: '50mb' }
app.use(bodyParser.urlencoded({ extended: true }))
// app.use(bodyParser.urlencoded({ limit: '50mb', parameterLimit: 1000000, extended: true }))


function imageFilter(req, file, callback) {
	if (file.originalname.toLowerCase().match(/\.(jpg|jpeg|png|bmp|gif)$/))
		callback(null, true)
	else
		callback(new Error('Only image files are allowed!'), false)
}

// const imagesUpload = multer({ dest: `${UPLOAD_PATH}/`, fileFilter: imageFilter })
const imagesUpload = multer({
	storage: multer.diskStorage({
		destination: './uploads',
		filename: (req, file, cb) => { cb(null, file.originalname.split('.')[0]+'-'+Date.now()+'.'+file.originalname.split('.').pop().toLowerCase()) }
	}),
	fileFilter: imageFilter,
	limits: { fileSize: 52428800 } // 50 MB
}).array('images')




function uploadImages(req, res) {
	console.log(req.files)
	//...
}


app.post('/api/images', imagesUpload, uploadImages)