How to Upload File using MERN Stack?


Specifically, the file upload MERN stack was the subject of this article, which was intended to provide everything you needed to know.

Creating instances of the server and client

We need to develop a React application, therefore I’m assuming you’ve already installed NodeJS, MongoDB, and npm.

Clone a Starter Repo


git clone
cd ./file-upload-starter
npm install

From Scratch

Open the terminal and create a react project sing npm/npx

npx create-react-app file-upload

Folder Structure

The folder structure of React App

Running the above command generates a new react application. Now it’s time to install a package axios that is a promised-based HTTP client for JavaScript.

npm install axios

Now it’s time time to create a directory for the server with files for the server and model.

mkdir server
cd ./server
npm init -y
touch server.js
touch model.js
mkdir uploads

Final Folder structure


Creating Frontend

For creating a frontend user interface to upload files. In src/App.js

import React, { useState } from 'react';
import './App.css';
import axios from 'axios';

const App = () => {

  const [file, setfile] = useState()
  const onFormSubmit = (e) => {
      const formData = new FormData();
      formData.append("myfile", file[0]);"http://localhost:5000/fileupload",formData)
          .then((response) => {
              alert("The file is successfully uploaded");
          }).catch((error) => {

  const onChange = (e) => {

      return (
          <form onSubmit={(e)=>onFormSubmit(e)}>
              <h1>File Upload</h1>
              <input type="file" className="file-input" name="myImage" onChange= {(e)=>onChange(e)} />
              <button className="upload-button" type="submit">Upload</button>

export default App;

Starting React development server

npm run start

Database Model

In server/model.js

const mongoose = require('mongoose');

const fileSchema = new mongoose.Schema({

const FileModel = mongoose.model("file",fileSchema);

module.exports = FileModel

Creating a Server

In order to create a node server, we first need to install some packages

cd server
npm i express
npm i mongoose
npm i multer

Express is the API library for nodeJS. Mongoose is a MongoDB object modeling tool aka nodeJS driver. Multer is a node.js middleware for handling multipart/form-data.

In your server.js file

const express = require("express");
const path = require("path");
const multer = require("multer");
const mongoose  = require("mongoose");
const cors = require('cors')
const app = express();
const PORT = 5000;
const FileModel = require("./model")

const router = express.Router();

const storage = multer.diskStorage({
   destination: "./uploads/",
   filename: function(req, file, cb){
      cb(null,"IMAGE-" + + path.extname(file.originalname));

const upload = multer({
   storage: storage,
   limits:{fileSize: 1000000},

const obj =(req,res,next) => {
 try {    
    upload(req, res,  () => {

 } catch (error) {
}"/fileupload", obj, async (req,res)=>{
    try {     
        const file = new FileModel();
        file.path = req.file.path;
    } catch (error) {


   return res.send("<p>hello!</p>");

mongoose.connect("mongodb://localhost:27017/fileupload").then(()=>{console.log("DB is connected")})

   console.log("+ app listen on port",PORT,"\u{1F525}\u{1F680}")

Now start your node server

cd server
node server.js

Exporting files to the client side

app.use("/uploads",express.static(path.join(__dirname, "./uploads/")));

Simply by utilizing Express to export a file as a static asset, you must make the files Directory public.


The client retrieves data from many origin APIs, which can result in a CORS permission problem. This can be fixed in your browser by permitting all origins or by using a library, as we briefly covered in our discussion of the MERN stack development.

Sudeep Mishra

Sudeep Mishra


%d bloggers like this: