react顯示文件上傳進(jìn)度的示例
更新時間:2021年04月16日 09:08:15 作者:阿政想暴富
這篇文章主要介紹了react顯示文件上傳進(jìn)度的示例,幫助大家更好的理解和學(xué)習(xí)使用react,感興趣的朋友可以了解下
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
在使用react, vue框架的時候, 如果需要監(jiān)聽文件上傳可以使用axios里的onUploadProgress.
react上傳文件顯示進(jìn)度 demo
前端 快速安裝react應(yīng)用
確保有node環(huán)境 npx create-react-app my-app //當(dāng)前文件夾創(chuàng)建my-app文件 cd my-app //進(jìn)入目錄 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,
});
//請求本地服務(wù)
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服務(wù)器
1.先創(chuàng)建文件夾webSever cd webSever npm -init -y //創(chuàng)建package.json文件 2.安裝express 以及文件上傳需要的包 npm install express multer ejs 3.創(chuàng)建app.js
app.js
var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs')
var multer = require('multer')
//設(shè)置跨域訪問
app.all("*", function (req, res, next) {
//設(shè)置允許跨域的域名,*代表允許任意域名跨域
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 即可實現(xiàn)
以上就是react顯示文件上傳進(jìn)度的示例的詳細(xì)內(nèi)容,更多關(guān)于react顯示文件上傳進(jìn)度的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react中如何對自己的組件使用setFieldsValue
react中如何對自己的組件使用setFieldsValue問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
React創(chuàng)建虛擬DOM的兩種方式小結(jié)
本文主要介紹了兩種創(chuàng)建React虛擬DOM的方式,包括JS方式和jsx方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
React Native之prop-types進(jìn)行屬性確認(rèn)詳解
本篇文章主要介紹了React Native之prop-types進(jìn)行屬性確認(rèn)詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12

