Search code examples
node.jsexpressmulter

Uploaded image not working with multer


I am trying to upload a picture with express and multer. Here is the form I use to upload the image:

<form action="/uploadProfilePicture" method="POST" id="form-upload-profile-picture">
  <div class="row center">
      <div class="row">
          <input type="file" name="uploadProfilePicture" id="add-friend-search-input">
      </div>
      <div class="row">
          <button class="button-green-large" class="u-full-width" id="add-friend-search-submit">Upload</button>
      </div>
  </form>

And here is my back end:

var mkdirp           = require("mkdirp"),
    multer           = require("multer");

// MULTER CONFIGURATION
    var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        //var code = JSON.parse(req.body.model).empCode;
        var dest = "/public/images";
        mkdirp(dest, function (err) {
            console.log(dest);
            if (err) cb(err, dest);
            else cb(null, dest);
        });
    },
    filename: function (req, file, cb) {
        cb(null, Date.now()+'-'+file.originalname);
    }
});

// POST ROUTE: Upload profile picture
app.post("/uploadProfilePicture", upload.any(), function(req, res) {
    console.log(req.body);
    res.send(req.files);
});

However, whenever I upload an image, it does not appear in /public/images. What is wrong with my code? Thanks so much!


Solution

  • enctype="multipart/form-data" is missing in your html form tag. Without that, it will post your form as application/x-www-form-urlencoded, which will not include any file data.