How to implement a progress bar for file uploads in a React.js app



Image not found!!


Implementing a progress bar for file uploads in a React.js app involves a combination of frontend and backend code. Here's a basic example using the popular axios library for making HTTP requests and a simple Node.js/Express server on the backend.

Frontend (React.js)

  1. Install Axios: Make sure you have Axios installed in your React.js project.

    bash
    npm install axios
  2. Create a file upload component: Create a component for file uploads. Let's call it FileUpload.js.

    jsx
    import React, { useState } from 'react'; import axios from 'axios'; const FileUpload = () => { const [file, setFile] = useState(null); const [progress, setProgress] = useState(0); const onFileChange = (e) => { setFile(e.target.files[0]); }; const onUpload = async () => { const formData = new FormData(); formData.append('file', file); try { await axios.post('/api/upload', formData, { onUploadProgress: (progressEvent) => { const percentage = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgress(percentage); }, }); console.log('File uploaded successfully'); } catch (error) { console.error('Error uploading file: ', error); } }; return ( <div> <input type="file" onChange={onFileChange} /> <button onClick={onUpload}>Upload</button> {progress > 0 && <div>Progress: {progress}%</div>} </div> ); }; export default FileUpload;

Backend (Node.js/Express)

  1. Install necessary packages: Make sure you have Express and multer (middleware for handling multipart/form-data) installed.

    bash
    npm install express multer
  2. Create a simple Express server: Create a file, let's call it server.js.

    javascript
    const express = require('express'); const multer = require('multer'); const app = express(); const port = 5000; const storage = multer.memoryStorage(); const upload = multer({ storage: storage }); app.post('/api/upload', upload.single('file'), (req, res) => { // Do something with the file (e.g., save it to disk, process it, etc.) // For now, we'll just send a success response. res.send('File uploaded successfully'); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
  3. Run your server: Start your Node.js server using the following command:

    bash
    node server.js

Now, when you run your React app and use the FileUpload component, it should display a progress bar as the file is being uploaded to the server.

Note: This is a basic example, and in a production environment, you might want to handle errors more gracefully, secure your file uploads, and implement additional features such as file validation and storage. Additionally, you might want to consider using a dedicated file storage service like Amazon S3 for production scenarios.