MERN Stack uploading files with Multer

Musab Abbasi
4 min readOct 20, 2022

--

In this tutorial we will be learning to upload files using Multer in MERN stack. Initially I will be using postmannode.js with express and multer, then I’ll integrate file upload API in react.js as well.

Pre-requisites

In this tutorial, I would assume you have a basic knowledge of React.js, Node.js and Express.js.

Now I have already made a basic layout for both backend and frontend that can be cloned from my GitHub repo on this link MuqtadirBillah/multer-mern (github.com).

First, you need to clone this repo. All you need to do is clone it by below command.

git clone https://github.com/MuqtadirBillah/multer-mern.git

Once you clone the repo, you need to install packages.

Installing frontend packages

All you need to do is navigate to the frontend folder via terminal and execute the below command.

npm inst

Installing backend packages

Now, you need to navigate to backend folder via terminal and execute the below command

npm install

Now once both frontend and backend is ready. You can open separate terminals for both and run “npm start” on frontend folder and “npm run dev” on backend folder terminal.

Frontend React.js Browser display
Backend terminal.

Now it both are running properly, we’ll move to our main topic i.e. multer. Multer is already installed on backend as it was defined in dependencies on my repo.

File Uploading on Backend (Node.js & Express.js)

Now all you need to do is simply add multer configs in your file route and multer will act as middleware to upload files.

const express = require("express");const fileController = require("../controllers/fileController")const fileRouter = express.Router();const multer  = require('multer')let storage = multer.diskStorage({destination: function (req, file, cb) {cb(null, './uploads')},filename: function (req, file, cb) {let extArray = file.mimetype.split("/");let extension = extArray[extArray.length - 1];cb(null, file.fieldname + '-' + Date.now()+ '.' +extension)}})const upload = multer({ storage: storage })fileRouter.route("/upload").post(upload.single('image'), fileController.fileUpload);module.exports = fileRouter;

Keep in mind that you need to add a folder called upload in your backend folder.

Next, we will move our file controller and add a function called file upload, export it in the end and simply responding with the uploaded file name.

const moment = require("moment");const fileUpload = (req, res)=>{console.log(req.file);try{res.send({ status: "success", message: `${req.file.originalname} uploaded!` })} catch(err){res.send({ status: "err", error: err })}}module.exports = {fileUpload}

Now, to test if the file is uploading, we will use Postman. We will create a post request and send file as form data.

You can select image instead of text in postman by hovering over it.

Let’s send a request.

Now, we have received a response saying that our file is uploaded. If you check the uploads folder, you’ll see the uploaded file in it.

Now that we are able to upload files on backend, let’s attach react.js to it.

File Uploading from Frontend(React.js)

I will be working on app.js/jsx as it is just a tutorial. you can use any other custom component if you want.

I am adding a simple input file and at the top, I have initialized a state and saving file on the change of it. Then, onclick of the button I am running upload file function. In that function I am initializing formData and appending file that was save in state into that formData. Next, I am simply using axios to make post request and showing success message on alert box.

import logo from './logo.svg';import './App.css';import axios from "axios";import { useState } from 'react';function App() {var [file, setFile] = useState();const uploadFile = ()=>{const formData = new FormData();formData.append("image", file);console.log(formData);axios.post("http://localhost:5000/api/file/upload", formData).then((response)=>{console.log(response)alert(response.data.message)}).catch(err=>console.log(err))}return (<div className=""><h1>File Uploader</h1><input type="file" onChange={(e)=>{ setFile(e.target.files[0]); console.log(e.target.files[0]) }} /><button onClick={()=>uploadFile()}>Upload File</button></div>);}export default App;

Now you know how to upload file on MERN stack via multer. In the upcoming blogs I will be writing on how to upload files on cloud i.e. cloudinary.

Follow me for more interesting tips and tricks at Musab Abbasi — Medium
You can also find me on LinkedIn and Github

--

--

Musab Abbasi
Musab Abbasi

Written by Musab Abbasi

Computer Science Graduate with MERN stack website development expertise.