Skip to content

Instantly share code, notes, and snippets.

@rayterrill
Created January 10, 2018 20:19
Show Gist options
  • Select an option

  • Save rayterrill/8ca484fe0e6ecf820b51eebd766ceae8 to your computer and use it in GitHub Desktop.

Select an option

Save rayterrill/8ca484fe0e6ecf820b51eebd766ceae8 to your computer and use it in GitHub Desktop.
Upload images to Mongo with NodeJS and Express
var express = require('express');
var mongoose = require('mongoose');
var ObjectId = require('mongoose').Types.ObjectId;
var fs = require('fs-extra');
var url = 'mongodb://username:password@server/mydb';
var multer = require('multer');
var upload = multer({limits: {fileSize: 1064960 },dest:'/uploads/'}).single('picture');
var app = express();
// Default route http://localhost:3000/
app.get('/', function(req, res){
res.send('yo');
});
// Form POST action handler
app.post('/uploadpicture', function (req, res) {
upload(req, res, function (err) {
if (err) {
res.status(500).json({ error: 'message' });
}
if (req.file == null) {
// If Submit was accidentally clicked with no file selected...
res.send('boo');
} else {
// read the img file from tmp in-memory location
var newImg = fs.readFileSync(req.file.path);
// encode the file as a base64 string.
var encImg = newImg.toString('base64');
// define your new document
var newItem = {
description: req.body.description,
contentType: req.file.mimetype,
size: req.file.size,
img: Buffer(encImg, 'base64')
};
db.collection('images').insert(newItem)
.then(function() {
console.log('image inserted!');
});
res.send('yo');
}
});
});
var PORT = process.env.PORT || 3000;
//use the PORT environment variable if it exists, or 3000
//connect to the database
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
//fire up express and listen
app.listen(PORT);
console.log('Listening on port ' + PORT);
});
@darshil8488
Copy link
Copy Markdown

,khjkljk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment