NodeJS File Upload Tutorial with Examples

Welcome to our NodeJS file upload tutorial. We will cover server-side processing of a file using two middleware libraries. If you’re interested in client-side file uploads, check out some of our front end tutorials.

Let’s start by using express-generator to create a basic scaffold.

$ npm install -g express-generator
$ express myapp
In the main upload route, we will parse the file and save it to a directory.
So let’s make the directory in our project beforehand
$ cd myapp
$ npm i
$ mkdir uploads

1. Using express-fileupload

Let’s explore a library with a simple interface.

$ npm install --save express-fileupload

let expressFileupload = require(‘express-fileupload’)

app.use(expressFileupload({
limits: { fileSize: 50 * 1024 * 1024 },
abortOnLimit: true,
}))

app.post(‘/uploadFile’, async (req, res) => {
console.log(req.files.file)
await req.files.file.mv(`${__dirname}/uploads/${req.files.file.name}`)
res.send(‘Uploaded’)
})

Express-fileupload is very easy to use but has the drawback of storing the full file in memory. This exposes your server to the risk of someone uploading an extremely large file, causing your server to run out of memory.

2. Using connect-busboy

Connect-busboy uses streams to work with uploads and is much more memory efficient. We’ll install it as a dependency.

<code>$ npm install --save connect-busboy

In the app.js file, add the middleware before the upload route:

let busboy = require('connect-busboy')
...
app.use(busboy());

Our Main upload route definition is as shown below.

app.post('/uploadFile', (req, res) => {
 req.busboy.on('file', function (fieldname, file, filename) {
   console.log("received file")
   var fstream = fs.createWriteStream('./uploads/' + filename);
   file.pipe(fstream);
   fstream.on('close', function () {
     res.send('upload succeeded!');
   });
 });
 req.pipe(req.busboy);
})

Next Steps

What we do next is up to your application logic, most apps will not keep files in an upload directory but rather transfer them to services like AWS S3. If you’re interested in learning about how to upload files to cloud storage, we have some tutorials on the topic (using vanilla JS, and using React). You can also try signing up for a Filestack account and using our SDKs which make file uploads very simple and secure.

 


Read More →

Ready to get started?

Create an account now!