react 파일 업로드 진행 예시 보이기

Axios는 promise 기반의 HTTP 라이브러리로 브라우저와 node에서 사용할 수 있습니다.js 중.
react, vue 프레임워크를 사용할 때, 파일 업로드를 감청하려면 axios의 onUploadProgress를 사용할 수 있습니다.

react 업로드 파일 표시 진도 데모


프런트엔드 빠른 설치react 응용 프로그램


 node 

npx create-react-app my-app // my-app 
cd my-app // 
npm install antd  // antd UI 

npm run start // 

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
    }
  }
  // 
  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로 웹 서버 탑재


1. webSever
  cd webSever
  npm -init -y  // package.json 

2. express  
  npm install express multer ejs

3. app.js

app.js


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 앱을 시작하면
이상은react가 파일 업로드 진도를 표시하는 예시의 상세한 내용입니다.react가 파일 업로드 진도를 표시하는 것에 대한 더 많은 자료는 저희 다른 관련 글을 주목해 주십시오!

좋은 웹페이지 즐겨찾기