Sometimes, we want to upload images using Node.js, Express, and Mongoose.
In this article, we’ll look at how to upload images using Node.js, Express, and Mongoose.
How to upload images using Node.js, Express, and Mongoose?
To upload images using Node.js, Express, and Mongoose, we canm use the bodyParser
middleware.
To use it, we write
app.use(express.bodyParser());
app.post('/todo/create', (req, res) => {
res.send(console.dir(req.files));
});
to call express.bodyParser
to return a middleware to parse multipart form data request bodies.
And then we call app.use
to use the middleware.
Then we create a POST route with app.post
.
And we get the uploaded files from req.files
in the route handler.
Then in the template, we write
form(action="/todo/create", method="POST", enctype="multipart/form-data")
input(type='file', name='todo')
button(type='submit') New
to add a form element with the action attribute set to /todo/create
to submit our form data to the route we just created.
We set enctype to multipart/form-data
to make it submit form data.
In the form element, we add a file input to let us accept files.
Conclusion
To upload images using Node.js, Express, and Mongoose, we canm use the bodyParser
middleware.