File Uploading using Multer in MERN Web Apps

Raguraj Sivanantham
5 min readMay 7, 2023

File uploading is a common feature in web applications that allows users to upload files from their local devices to the server. It is often used in applications that require users to upload documents, images, or other types of files, such as social media sites, e-commerce websites, or content management systems.

To enable file uploading in a web application, developers can use various libraries and tools, such as Multer, which is a middleware for handling multipart/form-data, a format used for file uploading. Multer makes it easy to handle files in a Node.js application, by providing features such as file filtering, file size limits, and automatic file renaming.

Let’s see how to implement file upload in MERN Application using Multer.

Create React App Using:

npx create-react-app client
npm install axios

Create Backend Using:

create a server folder. Inside the server folder, run the following command

npm init -y
npm install express multer cors nodemon uuid path

In the Client folder in the App.js,

replace the code with the following code

This is a React component that contains a form for submitting a CV (Curriculum Vitae). The form includes two fields: an input field for the user to enter their index number, and a file input field for the user to upload their CV. The file input field accepts only zip, rar, or 7zip file formats, and the file size should be less than 5 MB.

The form is submitted using an HTTP POST request to a local endpoint (“http://localhost:1337/cv/submitCV") using Axios. The form data is sent in a FormData object that includes the index number and the CV file. If the submission is successful, the server will send back a message that will be displayed in an alert box. If there is an error, a console log message will be displayed, and the user will be alerted with a “Network Error” message.

The state of the component is managed using the useState hook, which updates the indexNumber and file variables based on user input. The handleSubmit function is called when the user clicks the “Submit Your CV” button, preventing the default form submission behavior and sending the form data to the server using Axios. Finally, the component is exported using the default keyword to make it available for use in other parts of the application.

In the Server folder in the server.js

create “multer” folder inside the server folder.
create “uploads” folder inside the server folder.
inside the multer folder create file “cvUpload-config.js”

in cvUpload-config.js file,

This is a Node.js module that uses the Multer library to handle file uploads. The module exports a cvUpload object that can be used as middleware to handle the file upload process.

The module starts by importing the Multer library, UUIDv4 library, and the path module. It then defines a storage object that determines the destination folder and filename of the uploaded file. The destination folder is set to “./uploads”, and the filename is generated using UUIDv4 to ensure a unique name and the current timestamp to avoid filename collisions. The fileFilter function is used to filter the uploaded files based on their MIME type and file extension. It only allows certain MIME types and file extensions that are defined in the allowedFileTypes and allowedExtensions arrays, respectively.

After defining the storage and fileFilter objects, the module creates a Multer object using the multer() function and passing the storage, fileFilter, and limits objects as options. The limits object is used to limit the maximum file size to 5 MB. (In line 31, limits: { fileSize: 1024 * 1024 * 5 } means, KB * MB * 5, So, 5MB)

Finally, the module exports the cvUpload object, which can be used as middleware to handle the file upload process. The cvUpload object can be included as middleware in a route handler to handle the file upload and validate the file’s MIME type and extension before storing it on the server.

create “routes” folder inside the server folder,
inside the routes folder create file “submitcv.js”

in submitcv.js,

This is a Node.js code that defines a route for submitting CVs. It requires the “express” framework and a “cvUpload” middleware which is defined in a separate file. It also requires “MulterError” from the “multer” middleware.

The code defines a router called “submitCV” and defines a POST request handler that accepts a single file named “cv”. It then checks for any Multer errors using the “findMulterError” function, which is a middleware that checks for file size and file type errors. If there are no errors, it logs the index number and file details to the console and returns a JSON response indicating that the submission was successful. If there are any errors, it returns a JSON response indicating that the submission failed.

Create server.js inside the server folder and paste the following code,

This code sets up a basic Express server that listens on port 1337 and responds to HTTP requests. The server uses the CORS middleware to enable Cross-Origin Resource Sharing with a specified origin. The `app.use(require(“./routes/submitcv”))` line sets up a route for the `/cv/submitCV` endpoint using the `submitCV` router defined in the `./routes/submitcv.js` file. When the server receives a GET request to the root URL (`/`), it responds with a JSON object containing a message indicating that the server is running and active. When the server is started, it logs a message to the console indicating that it is running on port 1337.

Samples,

when user enter the index number and select file click submit,
In the frontend, when the user enters the index number and selects the file click submit
In back end, when the user enters the index number and selects the file click submit
In the backend, when the user enters the index number and selects the file click submit
when file is not selected
when file size is greater than 5MB

Find the Source of the code of the following tutorial in GitHub.

--

--

Raguraj Sivanantham

MERN Stack, Laravel, CodeIgniter | IT Enthusiast | Undergraduate at University of Moratuwa | B.Sc (Hons.) in Information Technology and Management