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:
| |
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.
multipart/form-dataIf 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-datatext/plain
You just have to use the multipart encoding whenever you’re sending file data.
- 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:
| |
That’s it!
On the client form, you’ll have to use a form that looks like this:
| |
If you need to handle multiple files (an array), you can use the following:
| |
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!