您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關如何實現react顯示文件上傳進度demo的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
在使用react, vue框架的時候, 如果需要監聽文件上傳可以使用axios里的onUploadProgress.
確保有node環境 npx create-react-app my-app //當前文件夾創建my-app文件 cd my-app //進入目錄 npm install antd //安裝antd UI組件 npm run start //啟動項目
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 }}> <h3>{this.state.baifenbi + '%'}</h3> <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;
1.先創建文件夾webSever cd webSever npm -init -y //創建package.json文件 2.安裝express 以及文件上傳需要的包 npm install express multer ejs 3.創建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 app 即可實現
感謝各位的閱讀!關于“如何實現react顯示文件上傳進度demo”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。