Bill
Bill

Reputation: 87

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.use(bodyParser.json());
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
})

app.post('/', multer({ dest: './public/uploads/'}).single('upl'), function(req,res){
    console.log(req.body); //form fields
    console.log(req.file); //form files
    res.status(204).end();
});

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

Index.ejs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Pulse</title>
  </head>
  <body>

    <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">
    </form>


  </body>

</html>

Upvotes: 2

Views: 8682

Answers (2)

Bill
Bill

Reputation: 87

var storage = multer.diskStorage({
destination: function (req, file, cb) {
 cb(null, './uploads/');
    },
 filename: function (req, file, cb) {
    var originalname = file.originalname;
    var extension = originalname.split(".");
    filename = Date.now() + '.' + extension[extension.length-1];
    cb(null, filename);
  }
});

router.post('/', multer({storage: storage, dest: './uploads/'}).single('uploads'), function(req,res){
  var music = new Music ({
    fieldname: req.file.fieldname,
    originalname: req.file.originalname,
    encoding: req.file.encoding,
    mimetype: req.file.mimetype,
    destination:req.file.destination,
    filename: req.file.filename,
    path: req.file.path,
    size: req.file.size
  })
  music.save(function(err){
    if (err){console.log(err)}
    else {
      res.redirect('/');
    }
  })
});

model

var mongoose = require('mongoose');

var musicSchema = new mongoose.Schema({
  fieldname: String,
  originalname: String,
  encoding: String,
  mimeptype: String,
  destination: String,
  filename: String,
  path: String,
  size: Number,
  created_at: Date,
  updated_at: Date
});
var Music = mongoose.model('Music', musicSchema);

module.exports = Music;

based on what deathnote said, this worked for me.

Upvotes: 2

DeathNote
DeathNote

Reputation: 264

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

app.post('/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.

Upvotes: 0

Related Questions