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.
- Server (Node.js with Express.js):
Install required packages using npm:
npm install express multer cors
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}`);
});
- Client (React):
Install required packages using npm:
npm install axios react-dropzone react-progress-bar-plus
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;
- 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;
- Run the application:
Start your server:
node server.js
Start your React app:
npm start
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.
Support My Work โค๏ธ
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me ๐
Letโs stay connected! You can follow me or reach out on these platforms:
๐น YouTube โ Tutorials, insights & tech content
๐น LinkedIn โ Professional updates & networking
๐น GitHub โ My open-source projects & contributions
๐น Instagram โ Behind-the-scenes & personal updates
๐น X (formerly Twitter) โ Quick thoughts & tech discussions
Iโd love to hear from youโwhether itโs feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)