title: node.js multer rename uploaded file
body: <p>I am trying to rename an image file uploaded with multer by the request parameters.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>router.route('/upload/:userid')
  .post(multer({
      dest: 'uploads/'
      }), function(req,res){
              fs.readFile('uploads/' + req.files.file.name, function(err, data) {
                  fs.writeFile('uploads/' + req.params.userid + '.' + req.files.file.extension, data, function(err) {
                      fs.unlink('uploads/' + req.files.file.name, function(){
                          if(err) throw err;
                      });
                  }); 
              });
              res.json({ message: 'Successfully uploaded image!' });
  });
  </code></pre>
  
  <p>It works great but I was wondering if it exists something cleaner and easier with multer rename function.</p>
  
  <p>It already tried something like this:</p>
  
  <pre><code>router.route('/upload/:userid')
  .post(multer({
      dest: 'uploads/',
      rename: function(req,res) {
          return req.params.userid
      }
      }), function(req,res){
              res.json({ message: 'Successfully uploaded image!' });
  });
  </code></pre>
  
  <p>But it does not work because req is not populated yet (undefined).</p>
  
  <p>I use httpie to test my code with the following command:</p>
  
  <pre><code>http.exe -f POST http://localhost:8080/upload/171284 file@D:\....\cat.jpg
  </code></pre>
  
  <p>Is it possible to use rename function of multer to do what I do with fs?
  Or is there a better way?</p>
  
  <p>Thank you for your feedbacks.</p>
  
  <p>Thomas</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>My new code using diskStorage:</p>
  
  <pre><code>var storage = multer.diskStorage({
      destination: function (req, file, cb) {
      cb(null, 'uploads/')
    },
      filename: function (req, file, cb) {
      cb(null, req.params.userid + '-')
    }
  })
  
  var upload = multer({ storage: storage })
  
  router.route('/upload/:userid')
      .post(multer({
          storage: storage
      }), function(req,res){
          res.json({ message: 'Successfully uploaded image!' });
  });
  </code></pre>
  
  <p>That throws an error:</p>
  
  <pre><code>Error: Route.post() requires callback functions but got a [object Object]
  </code></pre>