Bill Bill - 1 year ago 322
Node.js Question

Uploading multer files (nodejs) to Mongo database

I followed a tutorial on how to upload files in node js using multer and have only started learning node js and express js not too long ago so I am a quite a beginner at this. As a result of the tutorial, when I click on submit in my index.ejs to upload a image/music file, I can see in my terminal that the file has been uploaded with the details and when I check my ./public/uploads folder, a file has been put in there as well.

What I want to know now is, how do I grab that data and put it in my mongo database and how can I view these images or play these music files in my index.ejs? I have not set up mongoose yet but I will be. My code so far:

My app.js

var express = require('express'); //to require express.js
var multer = require('multer'), //to require multer for uploading photos
bodyParser = require('body-parser'), //to require body-parser to grab json form data
path = require('path');

var upload = multer({ dest: 'public/uploads/' }) //giving upload a destination directory

var app = express(); //to use express
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public')); //to use style.css
app.set('view engine', 'ejs'); //to use ejs as template language
// app.use(bodyParser.urlencoded({ extended: false })); //to use body parser

app.get('/', function(req, res){ //using express for routing and printing out content
res.render('index'); //render it in html. In ejs, display what we want to display
})'/', multer({ dest: './public/uploads/'}).single('upl'), function(req,res){
console.log(req.body); //form fields
console.log(req.file); //form files

app.listen(3000,function(){ //using express to load the server
console.log('Pulse on port 3000!');


<!DOCTYPE html>
<meta charset="utf-8">

<h1> Hi </h1>

<form action="/" enctype="multipart/form-data" method="post">
<input type="text" name="title">
<input type="file" name="upload">
<input type="submit" value="Upload">



Answer Source

What you are trying to do is make use of filesystem storage mechanism. Multer gives you an option to select where the destination will be to save your file and you can extract the file's name (manipulation option is also there) now after the file is stored pass the file's url to your specific function and from there save its location in your mongo db.

Retrieve the image's url and do the needed.

Code Sample'/yourlink', fileuploadfunc.single('filename'), function1, routename.functionname);

function1 - this is called after the upload is done routename - is called after execution of function1

IF you are not making use of routes then in function1 you can do whatever you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download