Handling file upload in Nodejs
Using multer to handle multipart formdata from a html file

I was working with a sample form to get name and profile picture from people. I tried to upload the picture to a node server from a plain html file using fetch, but when I try to console the request in the api, the request body was actually empty {}. Then I came to know that multer is used to handle multipart data.
I thought of sharing the code snippet, so that it could be useful to beginners working on file uploads, like me.
In fileUpload.html, there is a name field and a profile picture field. The api call should happen when a file is uploaded. In fileUpload.js, I am using formdata. This is equivalent to the body type ‘ form-data’ in postman. I am appending the image and name to form data. We can append as many fields required. Then, I am making an api call to server using ‘fetch’.
In the server, multer acts as a middleware to process form data. The req.body contains username and req.files will give the file details. The format is
{ fieldname: 'image',
originalname: '108462_117201480614PM63.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads',
filename: '1603690932358',
path: 'uploads/1603690932358',
size: 51836 }
From here, the file is present in the given destination folder. We can upload to S3 or cloudinary, according to our application needs.