How to upload images using Node.js, Express, and Mongoose ?

How to upload images using Node.js, Express, and Mongoose ?

Asked on October 24, 2018 in node.js.
Add Comment


  • 3 Answer(s)

    Try this, it will be helpful:

    // 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');
    
    Answered on October 24, 2018.
    Add Comment

    Add bodyParser if your using express:

    app.use(express.bodyParser());
    

    then our route automatically has access to the uploaded file(s) in req.files:

    app.post('/todo/create', function (req, res) {
        // TODO: move and rename the file using req.files.path & .name)
        res.send(console.dir(req.files)); // DEBUG: display available fields
    });
    

    If name the input control “todo” :

    form(action="/todo/create", method="POST", enctype="multipart/form-data")
        input(type='file', name='todo')
        button(type='submit') New
    

    Then the uploaded file is ready by the time we can get the path and original filename in ‘files.todo’:

    req.files.todo.path, and
    req.files.todo.name

    other useful req.files properties:

    size (in bytes)
    type (e.g., ‘image/png’)
    lastModifiedate
    _writeStream.encoding (e.g, ‘binary’)

    Answered on October 24, 2018.
    Add Comment

    we can configure the connect parser middleware in a configuration block in your main application file:

    /** Form Handling */
    app.use(express.bodyParser({
        uploadDir: '/tmp/uploads',
        keepExtensions: true
    }))
    app.use(express.limit('5mb'));
    
    Answered on October 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.