title: Use Multer in Express Route? (Using MEANJS)
body: <p>I'm using <a href="https://www.npmjs.com/package/multer">Multer</a> 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).</p>
  
  <p>CURRENT, WORKING CODE</p>
  
  <p><strong>express.js</strong></p>
  
  <pre><code>// 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' &amp;&amp; file.mimetype !== 'image/jpeg' &amp;&amp; file.mimetype !== 'image/png') {
              return false;
          }
      }
  }));
  </code></pre>
  
  <p><strong>server_routes.js</strong></p>
  
  <pre><code>app.route('/users/image').post(server_controller_file.imageUpload);
  </code></pre>
  
  <p><strong>server_controller_file.js</strong></p>
  
  <pre><code>exports.imageUpload = function(req, res) {
  // Check to make sure req.files contains a file, mimetypes match, etc., then send appropriate server response.
  };
  </code></pre>
  
  <p><strong>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)...</strong></p>
  
  <pre><code>var multer = require('multer');
  exports.imageUpload = function(req, res) {
      multer({
          onFileUploadComplete: function(file) {
              res.send();
          }
      });
  }
  </code></pre>
  
  <p>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!</p>