How to Handle File Uploads in Node.js
Learn how to handle file uploads in Node.js using Express framework.
In a previous blog post, How to Upload a File Using Fetch, we discussed how to upload files to a server using the Fetch API. In this post, we will focus on using Node.js, specifically Express, to handle uploaded files.
To get started, you will need to install the express-fileupload
npm module:
1 | npm install express-fileupload |
Once installed, add it to your middleware. Here are two ways to do it:
1 | import fileupload from 'express-fileupload'; |
Make sure to include this middleware in your Express app, as it allows the server to parse file uploads.
When a file is uploaded, it will be available under req.files
. If you forget to add the express-fileupload
middleware, req.files
will be undefined
.
Now, let’s take a look at an example route for saving an image:
1 | app.post('/saveImage', (req, res) => { |
This is the minimal code required to handle file uploads in Node.js. We use the mv
property provided by the express-fileupload
module to move the uploaded file to the specified path. Then, we send a response to the client indicating the success or error status of the upload.
Tags: Node.js, file uploads, Express, middleware, express-fileupload