/

How to Handle File Uploads in Node.js

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
2
3
4
5
6
7
8
import fileupload from 'express-fileupload';
// or
const fileupload = require('express-fileupload');

app.use(
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.post('/saveImage', (req, res) => {
const image = req.files.myFile;
const path = __dirname + '/images/' + image.name;

image.mv(path, (error) => {
if (error) {
console.error(error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'error', message: error }));
return;
}

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'success', path: '/images/' + image.name }));
});
});

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