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

The difference between html form submission action and url jump to actiond

The action of the form is different from the URL j...

MySQL Daemon failed to start error solution

MySQL Daemon failed to start error solution A few...

How to install MySQL 5.7 on Ubuntu and configure the data storage path

1. Install MySQL This article is installed via AP...

Rules for using mysql joint indexes

A joint index is also called a composite index. F...

Summary of basic knowledge points of Linux group

1. Basic Introduction of Linux Group In Linux, ev...

Application example tutorial of key in Vue page rendering

introduction During the front-end project develop...

Vant Uploader implements the component of uploading one or more pictures

This article shares the Vant Uploader component f...

impress.js presentation layer framework (demonstration tool) - first experience

I haven’t blogged for half a year, which I feel a ...

MySQL replication advantages and principles explained in detail

Replication is to transfer the DDL and DML operat...

Mysql case analysis of transaction isolation level

Table of contents 1. Theory SERIALIZABLE REPEATAB...

Introduction and usage of Angular pipeline PIPE

Preface PIPE, translated as pipeline. Angular pip...

MySQL fuzzy query usage (regular, wildcard, built-in function)

Table of contents 1. MySQL wildcard fuzzy query (...

Solution to mysql prompt "got timeout reading communication packets"

Error message: user: 'root' host: `localh...