I’ve never uploaded a blob file to an express backend, or MongoDB before.

All the times that I’ve learned backend development, I was mainly handling JSON data types.

Which is why, when I tried sending a POST request to an express backend with a body that contains a File data type, this error occurred:

1
2
request entity too large
PayloadTooLargeError: request entity too large

After a quick googling, it turns out that there are a few things that I’ll need to know about “uploading” files to a DB through an express backend.

  1. multipart/form-data If you need to send files via a form, you’ll need to add this flag to the form tag: enctype='multipart/form-data'.

The reason is because when you make a POST request, you have to encode the data that forms the body of the request in some way.

There are 3 types of encoding:

  • application/x-www-form-urlencoded (default)
  • multipart/form-data
  • text/plain

You just have to use the multipart encoding whenever you’re sending file data.

  1. Using Multer On the Express backend, you have to use the multer middleware to handle the request. Multer is a middleware built specifically for handling multipart/form-data, which is used primarily for uploading files. Multer will not process any form which is not multipart.

To use multer, you can do the following:

1
2
3
4
5
6
7
const multer = require('multer')
const upload = multer({ dest: 'uploads/'})

app.post('/profile', upload.single('avatar'), (req, res, next) => {
    //req.file is the `avatar` file
    //req.body will hold the text fields, if there were any
})

That’s it!

On the client form, you’ll have to use a form that looks like this:

1
2
3
<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>

If you need to handle multiple files (an array), you can use the following:

1
2
3
4
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

Now, one last thing. Notice at the beginning you specify an upload variable, with a dest property of ‘uploads’. What is this?

So, when the server receives the request, it’ll need to save the file somewhere. This function specifies the folder in which the file is stored on the server’s DiskStorage.

That’s about it!