MERN Stack uploading files with Multer

Pre-requisites

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

Installing frontend packages

npm inst

Installing backend packages

npm install
Frontend React.js Browser display
Backend terminal.

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

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;
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}

File Uploading from Frontend(React.js)

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;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.