javascript 将图像上传到MongoDB - (NodeJS Express Multer && GridFsStorage)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 将图像上传到MongoDB - (NodeJS Express Multer && GridFsStorage)相关的知识,希望对你有一定的参考价值。

'use strict'
import express from 'express';
import bodyParser from 'body-parser';
import multer from 'multer';
import GridFsStorage from 'multer-gridfs-storage';
import crypto from 'crypto';

import mongoose from 'mongoose';
import path from 'path';



/* INIT */

const port = 3000;
const app = express()

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

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))



/* MONGODB */

const DATABASE_CONNECTION_URI = 'mongodb://db/test'

mongoose.connect(DATABASE_CONNECTION_URI, { useNewUrlParser: true })

const storage = new GridFsStorage({
	url: DATABASE_CONNECTION_URI,
	file: (req, file) => {
		return new Promise((resolve, reject) => {
			crypto.randomBytes(32, (err, buff) => {
				if (err) return reject(err)
				const filename = buff.toString('hex') + path.extname(file.originalname)
				const fileInfo = {
					filename,
					bucketName: 'images'
				}
				resolve(fileInfo)
			})
		})
	}
})

const imagesUpload = multer({
	fileFilter: imageFilter,
	storage
}).array('images')



// CONNECTION EVENTS
mongoose.connection.on('connected', () => {
	console.log('Mongoose default connection open to ' + DATABASE_CONNECTION_URI);
});

mongoose.connection.on('error', err => {
	console.log('Mongoose default connection error: ' + err);
});

mongoose.connection.on('disconnected', () => {
	console.log('Mongoose default connection disconnected');
});

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {  
	mongoose.connection.close(() => {
		console.log('Mongoose default connection disconnected through app termination');
		process.exit(0);
	});
});




/* ROUTES */

app.post('/api/analyze/images', imagesUpload, () => {
  console.log(req.files)
})



/* LISTEN */

app.listen(port, () => {  
	console.log(`Listening on port ${port}!`)
})

以上是关于javascript 将图像上传到MongoDB - (NodeJS Express Multer && GridFsStorage)的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 multer 模块将图像上传到 mongodb

如何使用 node js 将图像上传并保存到 mongodb

如何将上传的图像保存到 MongoDB 集合并检索它

使用 Multer 将图像上传到 mongoDB 时 Heroku 出错

使用 Nodejs、Express、Mongoose 和 React 将图像上传到 MongoDB

使用 mongoose 通过 React 应用程序将图像上传到 mongodb 数据库