title: Using multer to save a base64 decoded image to a user collection and disk
body: <p>I have this two codes. first one uses multer to save a user with an image. For each user, it saves the uploaded image with a particular name in the avatar field and the same name for the image. if no image is uploaded then save noimage.png as a name in the avatar field.</p>
  
  <p>The second one decodes a base64 string to a picture and saves it to the specific path but every time an image is uploaded is being overwritten.</p>
  
  <p>Is it possible to implement both codes to have the functionality of the first one but decoding the image from a base64 string?</p>
  
  <p>The base64 string is the result of a cropped image. I want the user to be able to crop an area of the image to display it as the avatar.</p>
  
  <p>Thanks in advance.</p>
  
  <pre><code>// Register Proccess
  router.post('/register', upload.single('avatar'), function(req, res){
  
  
    const username  = req.body.username;
    const email     = req.body.email;
    const password  = req.body.password;
    const password2 = req.body.password2;
    const date      = new Date();
  
  
    if(req.file){
      var avatar    = req.file.filename;
    } else {
      var avatar    = 'noimage.png';
    }
  
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
  
    let {errors, validationResults} = require('express-validator');
  
    if(errors){
      res.render('register', {
        errors:errors
      });
  
    } else{
  
      let newUser = new User({
        username:username,
        email:email,
        password:password,
        date: date,
        avatar: avatar
      });
      bcrypt.genSalt(10, function(err, salt){
        bcrypt.hash(newUser.password, salt, function(err, hash){
          if(err){
            console.log(err);
          }
          newUser.password = hash;
          newUser.save(function(err){
            if(err){
              console.log(err);
              return;
            } else {
              req.flash('success','You are now registered and can log in');
              res.redirect('/');
            }
          });
  
        });
      });
    })
  });
  </code></pre>
  
  <p>Second code</p>
  
  <pre><code>var upload = multer(); 
  
  router.post('/crop', upload.single('avatar'), function(req, res) {
      let img = req.body.cropped;
      let image = img.split(';base64,').pop();
  
      fs.writeFile("public/images/uploads/out.png", image, {encoding: 'base64'}, function(err) {
      console.log('File created');
       if(err){
          console.log(err);
          return;
        } else {
          res.redirect('/crop');
        }
  }); 
    });
  </code></pre>