Search code examples
javascriptnode.jsexpresshttp-postmulter

express upload file with multer not working with urlencodedParser


I am trying to upload an image with a post request form. In my express.js server I am both using multer and urlencodedParser, because I am passing all the html inputs as a json object through the post request body plus a selection of a file, which I am handeling it with multer.

Here is the HTML code for the form:

<form action="http://localhost:8000/api/addOrgs" method="post">
    <div class="form-row">
        <!-- OTHER CODE -->
            <div class="form-group col-md-6">
                <label>Image or Logo</label>
                <input type="file" class="form-control" name="image" id="fileToUpload">
            </div>
        <button class="btn btn-primary">  Add the organization to the system</button>
    </div>
</form>

I have set up the multer:

// add image to folder
var multer  = require('multer')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../public/images/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

var upload = multer({ storage: storage })

Here is the express post request handler:

// to add a new organization to the list
app.post('/api/addOrgs', upload.single('imageToUpload'), urlencodedParser, (req, res)=> {
    try {
        var newobj = req.body;

        // want to change name of id in obj
        // add image name and delete image field
        newobj['img'] = newobj.image;
        delete newobj.image;

        // read orgs file
        let orgs = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../orgs.json')));
        
        //... OTHER CODE
        // send respond
        res.send('<h1>Successfully added!</h1><br><p>'+JSON.stringify(newobj, null, 4)+'</p></br><b>Now you can go <a href="/good">BACK</a></b>')
       // OTHER CODE
    } catch (e) {
        // ... OTHER CODE
    }
});

The problem is that I successfully have the name of the file uploaded in the json object sent through the req.body but it does NOT save the file in the folder. Is the problem coming from the usage of urlencodedParser for the app.post() parameter?

Or do I have to do something in order to save the file inside my app.post() function?


Solution

  • The file's form should have enctype="multipart/form-data" attribute. Try this, and it should work