How to Upload File using MERN Stack?

Share

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

Repo: https://github.com/CodewithSudeep/file-upload-starter

git clone https://github.com/CodewithSudeep/file-upload-starter.git
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

mern

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) => {
      e.preventDefault();
      const formData = new FormData();
      formData.append("myfile", file[0]);
  
      axios.post("http://localhost:5000/fileupload",formData)
          .then((response) => {
              alert("The file is successfully uploaded");
          }).catch((error) => {
      });
  }

  const onChange = (e) => {
      setfile(e.target.files);
  }

      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>
          </form>
      )
  
}

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({
    path:{}
});

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();
app.use(express.json({}))
app.use(cors())
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-" + Date.now() + path.extname(file.originalname));
   }
});

const upload = multer({
   storage: storage,
   limits:{fileSize: 1000000},
}).single("myfile")

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

 } catch (error) {
    console.log(error)  
 }
}

router.post("/fileupload", obj, async (req,res)=>{
    try {     
        const file = new FileModel();
        file.path = req.file.path;
        await file.save()
        res.status(200).send({"msf":"Dd"});
    } catch (error) {
        console.log(error)
    }
});

app.use(router);

app.get("/",(req,res)=>{
   return res.send("<p>hello!</p>");
});

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

app.listen(PORT,()=>{
   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.

Conclusion

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.

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: