DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to create file-uploading system with progress bar in MERN stack?

Creating a file uploading system with a progress bar in the MERN (MongoDB, Express.js, React, Node.js) stack involves several steps. Below, I'll outline a simple example using popular libraries for each part of the stack. Keep in mind that this is a basic implementation, and you may need to customize it based on your specific requirements.

  1. Server (Node.js with Express.js):

Install required packages using npm:

   npm install express multer cors
Enter fullscreen mode Exit fullscreen mode

Create a server file (e.g., server.js):

   const express = require('express');
   const multer = require('multer');
   const cors = require('cors');
   const path = require('path');

   const app = express();
   const port = process.env.PORT || 5000;

   app.use(cors());

   // Multer configuration for handling file uploads
   const storage = multer.memoryStorage();
   const upload = multer({ storage });

   // API endpoint for file upload
   app.post('/upload', upload.single('file'), (req, res) => {
     // Process the uploaded file here (e.g., save to MongoDB, return file details)
     // For demonstration purposes, just send a success response
     res.json({ message: 'File uploaded successfully' });
   });

   app.listen(port, () => {
     console.log(`Server is running on port ${port}`);
   });
Enter fullscreen mode Exit fullscreen mode
  1. Client (React):

Install required packages using npm:

   npm install axios react-dropzone react-progress-bar-plus
Enter fullscreen mode Exit fullscreen mode

Create a React component (e.g., FileUploader.js):

   import React, { useState } from 'react';
   import axios from 'axios';
   import Dropzone from 'react-dropzone';
   import ProgressBar from 'react-progress-bar-plus';
   import 'react-progress-bar-plus/lib/progress-bar.css';

   const FileUploader = () => {
     const [file, setFile] = useState(null);
     const [uploadProgress, setUploadProgress] = useState(0);

     const handleDrop = (acceptedFiles) => {
       setFile(acceptedFiles[0]);
     };

     const handleUpload = async () => {
       const formData = new FormData();
       formData.append('file', file);

       try {
         const response = await axios.post('http://localhost:5000/upload', formData, {
           onUploadProgress: (progressEvent) => {
             const progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
             setUploadProgress(progress);
           },
         });
         console.log(response.data);
       } catch (error) {
         console.error('Error uploading file:', error.message);
       }
     };

     return (
       <div>
         <Dropzone onDrop={handleDrop} accept="image/*">
           {({ getRootProps, getInputProps }) => (
             <div {...getRootProps()} style={{ border: '2px solid #dfe5e5', padding: '20px', textAlign: 'center' }}>
               <input {...getInputProps()} />
               <p>Drag & drop an image file here, or click to select one</p>
             </div>
           )}
         </Dropzone>
         {file && (
           <div>
             <ProgressBar percent={uploadProgress} autoIncrement={true} />
             <button onClick={handleUpload}>Upload</button>
           </div>
         )}
       </div>
     );
   };

   export default FileUploader;
Enter fullscreen mode Exit fullscreen mode
  1. Integrate into your main React app:
   import React from 'react';
   import FileUploader from './FileUploader';

   const App = () => {
     return (
       <div>
         <h1>MERN File Upload with Progress Bar</h1>
         <FileUploader />
       </div>
     );
   };

   export default App;
Enter fullscreen mode Exit fullscreen mode
  1. Run the application:

Start your server:

   node server.js
Enter fullscreen mode Exit fullscreen mode

Start your React app:

   npm start
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser.

This is a basic example, and you may need to enhance it based on your specific use case, such as handling multiple file uploads, error handling, and integrating with MongoDB for storing file details.

Top comments (0)