react显示文件上传进度的示例

时间:2022-10-17 08:51:24

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
在使用react, vue框架的时候, 如果需要监听文件上传可以使用axios里的onUploadProgress.

react上传文件显示进度 demo

前端 快速安装react应用

?
1
2
3
4
5
6
7
确保有node环境
 
npx create-react-app my-app //当前文件夹创建my-app文件
cd my-app //进入目录
npm install antd  //安装antd UI组件
 
npm run start //启动项目

src-> App.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
    }
  }
  //文件上传改变的时候
  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
      })
    }
  }
  //点击上传
  handleUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('files[]', file);
    });
    this.setState({
      uploading: true,
    });
    //请求本地服务
    axios.post("http://127.0.0.1:5000/upload", formData, this.configs).then(res => {
      this.setState({
        baifenbi: 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;

后台 使用express搭载web服务器

?
1
2
3
4
5
6
7
8
1.先创建文件夹webSever
  cd webSever
  npm -init -y  //创建package.json文件
 
2.安装express 以及文件上传需要的包
  npm install express multer ejs
 
3.创建app.js

app.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs')
var multer = require('multer')
//设置跨域访问
app.all("*", function (req, res, next) {
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
    // //允许的header类型
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    // //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // 可以带cookies
    res.header("Access-Control-Allow-Credentials", true);
    if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
})
 
 
app.use(express.static(path.join(__dirname, 'public')));
//模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
 
app.get("/", (req, res, next) => {
    res.render("index")
})
//上传文件
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)

  前端启动之后,启动后台 node app 即可实现 

以上就是react显示文件上传进度的示例的详细内容,更多关于react显示文件上传进度的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/kongyijilafumi/p/13293409.html