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

Summary of MySql storage engine and index related knowledge

Storage Engine What is a database storage engine?...

Standard summary for analyzing the performance of a SQL statement

This article will introduce how to use explain to...

Brief Analysis of MySQL B-Tree Index

B-Tree Index Different storage engines may also u...

What are the new CSS :where and :is pseudo-class functions?

What are :is and :where? :is() and :where() are p...

How to create dynamic QML objects in JavaScript

1. Dynamically create objects There are two ways ...

MySQL 8.0.11 compressed version installation tutorial

This article shares the installation tutorial of ...

HTML code to add quantity badge to message button

HTML code: <a onclick="goMessage();"...

vue+springboot realizes login function

This article example shares the specific code of ...

Detailed steps to install MySQL 8.0.27 in Linux 7.6 binary

Table of contents 1. Environmental Preparation 1....

Vue basics MVVM, template syntax and data binding

Table of contents 1. Vue Overview Vue official we...

Apache Log4j2 reports a nuclear-level vulnerability and a quick fix

Apache Log4j2 reported a nuclear-level vulnerabil...

Vue realizes the logistics timeline effect

This article example shares the specific code of ...

Solution to the problem of saving format in HTML TextArea

The format of textarea can be saved to the databas...