Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading images using Node.js, Express, and Mongoose

Please consider newer answers that have more up-to-date information as things have changed over the years!

Since many new Node.js libraries are quickly being rendered obsolete and there are relatively few examples anyways I want to ask about uploading images using:

  • Node.js (v0.4.1)
  • Express (1.0.7)
  • Mongoose (1.1.0).

How have others done it?

I've found: node-formidable, but I am new to uploading images in general so I want to learn general stuff and ways of doing so using Node.js and Express.

like image 248
JohnAllen Avatar asked Mar 01 '11 01:03

JohnAllen


People also ask

Can Mongoose store images?

So for storing an image in MongoDB, we need to create a schema with mongoose. For that create the file `model. js` file and define the schema. The important point here is that our data type for the image is a Buffer which allows us to store our image as data in the form of arrays.


1 Answers

I'll answer my own question for the first time. I found an example straight from the source. Please forgive the poor indentation. I wasn't sure how to indent properly when copying and pasting. The code comes straight from Express multipart/form-data example on GitHub.

// Expose modules in ./support for demo purposes require.paths.unshift(__dirname + '/../../support');  /**  * Module dependencies.  */  var express = require('../../lib/express')   , form = require('connect-form');  var app = express.createServer(   // connect-form (http://github.com/visionmedia/connect-form)   // middleware uses the formidable middleware to parse urlencoded   // and multipart form data   form({ keepExtensions: true }) );  app.get('/', function(req, res){   res.send('<form method="post" enctype="multipart/form-data">'     + '<p>Image: <input type="file" name="image" /></p>'     + '<p><input type="submit" value="Upload" /></p>'     + '</form>'); });  app.post('/', function(req, res, next){    // connect-form adds the req.form object   // we can (optionally) define onComplete, passing   // the exception (if any) fields parsed, and files parsed   req.form.complete(function(err, fields, files){     if (err) {       next(err);     } else {       console.log('\nuploaded %s to %s'         ,  files.image.filename         , files.image.path);       res.redirect('back');     }   });    // We can add listeners for several form   // events such as "progress"   req.form.on('progress', function(bytesReceived, bytesExpected){     var percent = (bytesReceived / bytesExpected * 100) | 0;     process.stdout.write('Uploading: %' + percent + '\r');   }); });  app.listen(3000); console.log('Express app started on port 3000'); 
like image 188
JohnAllen Avatar answered Oct 12 '22 02:10

JohnAllen