React example showing file upload progress

React example showing file upload progress

Axios is a promise-based HTTP library that can be used in browsers and node.js.
When using react or vue framework, if you need to monitor file uploads, you can use onUploadProgress in axios.

React upload file display progress demo

Quickly install react application on the front end

Make sure you have a node environment npx create-react-app my-app //Create the my-app file in the current folder cd my-app //Enter the directory npm install antd //Install the antd UI component npm run start //Start the project

src->App.js

import React from 'react';
import 'antd/dist/antd.css';
import { Upload, message, Button, Progress } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

import axios from "axios"
axios.defaults.withCredentials = true

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      fileList: [],
      uploading: false,
      filseSize: 0,
      Baifenbi: 0
    }
  }
  //When the file upload changes, configs = {
    headers: { 'Content-Type': 'multipart/form-data' },
    withCredentials: true,
    onUploadProgress: (progress) => {
      console.log(progress);
      let { loaded } = progress
      let { filseSize } = this.state
      console.log(loaded, filseSize);
      let baifenbi = (loaded / filseSize * 100).toFixed(2)
      this.setState({
        baifenbi
      })
    }
  }
  //Click to upload handleUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('files[]', file);
    });
    this.setState({
      uploading: true,
    });
    //Request local service axios.post("http://127.0.0.1:5000/upload", formData, this.configs).then(res => {
      this.setState({
        Price: 100,
        uploading: false,
        fileList: []
      })
    }).finally(log => {
      console.log(log);
    })
  }
  onchange = (info) => {
    if (info.file.status !== 'uploading') {
      this.setState({
        filseSize: info.file.size,
        Baifenbi: 0
      })
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }


  render() {
    const { uploading, fileList } = this.state;
    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };
    return (
      <div style={{ width: "80%", margin: 'auto', padding: 20 }}>
        <h2>{this.state.baifenbi + '%'}</h2>
        <Upload onChange={(e) => { this.onchange(e) }} {...props}>
          <Button>
            <UploadOutlined /> Click to Upload
          </Button>
        </Upload>
        <Button
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{ marginTop: 16 }}
        >
          {uploading ? 'Uploading' : 'Start Upload'}
        </Button>
        <Progress style={{ marginTop: 20 }} status={this.state.baifenbi !== 0 ? 'success' : ''} percent={this.state.baifenbi}></Progress>
      </div>
    )
  }
}

export default App;

The backend uses express to carry the web server

1. Create the folder webSever first
  cd webSever
  npm -init -y //Create package.json file 2. Install express and the packages required for file upload npm install express multer ejs

3. Create app.js

app.js

var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs')
var multer = require('multer')
//Set up cross-domain access app.all("*", function (req, res, next) {
    //Set the domain name allowed to cross domain, * represents allowing any domain name to cross domain res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
    // //Allowed header types res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    // //Cross-domain allowed request methodsres.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // Cookies are allowed
    res.header("Access-Control-Allow-Credentials", true);
    if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
})


app.use(express.static(path.join(__dirname, 'public')));
//Template engine app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get("/", (req, res, next) => {
    res.render("index")
})
//Upload files app.post('/upload', (req, res, next) => {

    var upload = multer({ dest: 'upload/' }).any();
  
    upload(req, res, err => {
      if (err) {
        console.log(err);
        return
      }
      let file = req.files[0]
      let filname = file.originalname
      var oldPath = file.path
      var newPath = path.join(process.cwd(), "upload/" + new Date().getTime()+filname)
      var src = fs.createReadStream(oldPath);
      var dest = fs.createWriteStream(newPath);
      src.pipe(dest);
      src.on("end", () => {
        let filepath = path.join(process.cwd(), oldPath)
        fs.unlink(filepath, err => {
          if (err) {
            console.log(err);
            return
          }
          res.send("ok")
        })
  
      })
      src.on("error", err => {
        res.end("err")
      })
  
    })
  
  })
  

app.use((req, res) => {
    res.send("404")
})
app.listen(5000)

After the front-end is started, start the background node app to achieve

The above is the details of the example of how react displays the progress of file uploads. For more information about how react displays the progress of file uploads, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • React implementation example using Amap (react-amap)
  • Detailed explanation of virtual DOM and diff algorithm in react
  • How to use lazy loading in react to reduce the first screen loading time
  • How to run the react project on WeChat official account
  • How to write CSS elegantly with react
  • Encapsulate a simplest ErrorBoundary component to handle react exceptions
  • React Fiber structure creation steps
  • Detailed explanation of the use of Refs in React's three major attributes
  • Write a React-like framework from scratch
  • Understanding and using React useEffect

<<:  How to install MySQL database on Debian 9 system

>>:  How to get the real path of the current script in Linux

Recommend

MySQL reports an error: Can't find file: './mysql/plugin.frm' solution

Find the problem Recently, I found a problem at w...

Usage and description of HTML tag tbody

The tbody element should be used in conjunction wi...

HTML hyperlink a tag_Powernode Java Academy

Anyone who has studied or used HTML should be fam...

MySQL 8.0.12 Simple Installation Tutorial

This article shares the installation tutorial of ...

A pitfall and solution of using fileReader

Table of contents A pitfall about fileReader File...

Summary of JavaScript Timer Types

Table of contents 1.setInterval() 2.setTimeout() ...

Detailed explanation of common methods of JavaScript String

Table of contents 1. charAt grammar parameter ind...

Example of how to optimize MySQL insert performance

MySQL Performance Optimization MySQL performance ...

jQuery plugin to implement dashboard

The jquery plug-in implements the dashboard for y...

Vue implements multiple selections in the bottom pop-up window

This article example shares the specific code of ...

Vue + element dynamic multiple headers and dynamic slots

Table of contents 1. Demand 2. Effect 3. All code...

Solve the MySQL 5.7.9 version sql_mode=only_full_group_by problem

MySQL 5.7.9 version sql_mode=only_full_group_by i...

Configure Mysql master-slave service implementation example

Configure Mysql master-slave service implementati...

Detailed explanation of MySql view trigger stored procedure

view: When a temporary table is used repeatedly, ...