注意:本文代码只提供进度数值显示,未实现进度条的显示
一、下载进度
<div class="schedule">0</div>
<button onclick="download()">下载</button>
<script>
// 要设置为slow 3G才能看得到明显的效果
const schedule = document.querySelector(".schedule");
function download() {
const xhr = new XMLHttpRequest();
const downloadUrl = './img/Scenery.jpg';
xhr.open('GET', downloadUrl, true);
xhr.addEventListener('progress', function (event) {
if (event.lengthComputable) {
// lengthComputable判断所关联的资源是否具有可以计算的长度。否则 ,ProgressEvent.total 属性将是一个无意义的值。
let percentComplete = event.loaded / event.total; // 计算下载进度(比例)
schedule.innerText = percentComplete;
}
}, false);
xhr.send();
}
</script>
二、上传进度
JS代码
<div>
<input type="file" name="f" id="f" />
<button id="upload-btn" onclick="upload()">上传</button>
</div>
<script>
function upload() {
const f = document.querySelector('#f');
console.dir(f);
const fdata = new FormData();
fdata.append('file', f.files[0]);
$post('/ufile', fdata)
}
function $post(url, data) {
const xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.upload.addEventListener("progress", function (e) { // 也可以用ponprogress进行监听
if (e.lengthComputable) {
let percentComplete = e.loaded / e.total; // 计算上传进度(比例)
console.log(percentComplete);
}
})
xhr.send(data);
}
</script>
Python代码
app.py
from flask import Flask, render_template, request
from os import path
import time
import re
u_path = path.dirname(__file__)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ufile', methods=['post'])
def ufile():
try:
file = request.files['file']
r = re.search(r'(\.\S+)', file.filename)
fn = ""
if(r != None):
fn = r.group()
file.save(u_path + '/static/file/' + str(time.time())+fn) # 没有判断文件夹是否存在,需自己先创建一个
return 'success'
except Exception as e:
print(e)
return 'fail'
if __name__ == '__main__':
app.run(debug=True)
我的主页:https://blog.csdn.net/qq_29750277,有关于前端(Vue、electron...)、Python等