Search code examples
node.jsexpressmulter

Having trouble uploading a file with node using multer


This seems like a simple problem, but I've been spending a while trying to solve it and I can't quite figure out what's wrong. This is my frontend form that is making the request:

div#PreGA
    p PreGa.json:
    form(action="config/set/PreGa", name="pre-ga", method="post", enctype="multipart/form-data")
        input(type="file" value="Choose File" accept=".json")#choose-file-pre-ga
        input(type="submit" value="Upload")#upload-pre-ga

This is the route that should receive the request:

var upload = multer({ dest: 'uploads/' });

//set the JSON file for the pre-ga reported issues
router.post('/config/set/PreGa',ensureAuthenticated, upload.single('pre-ga'), function(req, res, next) {


    console.log(req.body);
    console.log(req.file);

});

The issue is that req.file, which should return the file, is undefined when the route is called.

This is one of the simplest use cases, and I can't figure out what's going wrong. It would greatly appreciate some help.


Solution

  • Your file input is missing a name attribute.