Use Multer in Express Route? (Using MEANJS)

aikorei picture aikorei · Jan 5, 2015 · Viewed 24.7k times · Source

I'm using Multer to upload images in Express 4. However, the examples all show Multer being defined in the express file as Middleware. I'd like to actually define some of the Multer behaviors in my app routing itself. Is this possible? The end result that I need is for my route function to recognize when the upload is finished before it sends the server response to the browser, so an image can be displayed to the user (right now I'm only getting a partial image displayed because the file hasn't finished uploading yet).

CURRENT, WORKING CODE

express.js

// Require Multer as module dependency.
var multer = require('multer');

// Using Multer for file uploads.
app.use(multer({
    dest: './public/profile/img/',
    limits: {
        fieldNameSize: 50,
        files: 1,
        fields: 5,
        fileSize: 1024 * 1024
    },
    rename: function(fieldname, filename) {
        return filename;
    },
    onFileUploadStart: function(file) {
        if(file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
            return false;
        }
    }
}));

server_routes.js

app.route('/users/image').post(server_controller_file.imageUpload);

server_controller_file.js

exports.imageUpload = function(req, res) {
// Check to make sure req.files contains a file, mimetypes match, etc., then send appropriate server response.
};

Ideally, my server_controller_file.js would contain some checks to make sure the file finished uploading, e.g. (note: this is hypothetical/desirable, not actual working code)...

var multer = require('multer');
exports.imageUpload = function(req, res) {
    multer({
        onFileUploadComplete: function(file) {
            res.send();
        }
    });
}

Again, right now the async nature of node is causing the browser to think the upload is complete as soon as it receives a successful response, so when I update the url to display the image, it only partially displays. Thanks for the help!

Answer

Aymen Mouelhi picture Aymen Mouelhi · Mar 19, 2015

Actually you can do what you want with another method:

var express = require('express');
var multer  = require('multer');
var upload = multer({ dest: './uploads/'});
var app = express();

app.get('/', function(req, res){
  res.send('hello world');
});

// accept one file where the name of the form field is named photho
app.post('/', upload.single('photho'), function(req, res){
    console.log(req.body); // form fields
    console.log(req.file); // form files
    res.status(204).end();
});

app.listen(3000);