Python 语言 Web 表单文件上传进度条的前端后端协同实现

Python阿木 发布于 1 天前 3 次阅读


Python语言Web表单文件上传进度条的前端后端协同实现

随着互联网技术的不断发展,文件上传功能已成为许多Web应用不可或缺的一部分。在用户上传大文件时,提供文件上传进度条可以提升用户体验,让用户了解文件上传的实时状态。本文将围绕Python语言,结合前端和后端技术,实现一个文件上传进度条的功能。

前端实现

1. HTML结构

我们需要创建一个HTML文件,用于展示上传界面和进度条。

html

文件上传进度条

progressBar {
width: 0%;
height: 20px;
background-color: blue;
text-align: center;
line-height: 20px;
color: white;
}

0%

2. JavaScript实现

接下来,我们需要编写JavaScript代码,用于处理文件上传事件,并实时更新进度条。

javascript
document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open('POST', this.action, true);

xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) 100;
document.getElementById('progressBar').style.width = percentComplete + '%';
document.getElementById('progressBar').textContent = Math.round(percentComplete) + '%';
}
};

xhr.onload = function() {
if (xhr.status === 200) {
alert('文件上传成功!');
} else {
alert('文件上传失败!');
}
};

xhr.send(formData);
});

后端实现

1. Python环境搭建

我们需要安装Flask框架,用于快速搭建Web服务器。

bash
pip install flask

2. Flask应用

接下来,我们需要编写Flask应用,用于处理文件上传请求。

python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file:
file.save(file.filename)
return jsonify({'message': 'File uploaded successfully'}), 200

if __name__ == '__main__':
app.run(debug=True)

3. 文件上传进度反馈

为了实现文件上传进度反馈,我们需要在后端获取文件上传进度,并实时发送给前端。

python
from flask import Flask, request, jsonify
import os

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file:
file.save(file.filename)
return jsonify({'message': 'File uploaded successfully'}), 200

@app.route('/upload/progress', methods=['GET'])
def upload_progress():
if not os.path.exists('upload_progress.txt'):
return jsonify({'progress': 0}), 200
with open('upload_progress.txt', 'r') as f:
progress = int(f.read())
return jsonify({'progress': progress}), 200

if __name__ == '__main__':
app.run(debug=True)

4. 前端获取进度

我们需要修改前端JavaScript代码,使其能够实时获取文件上传进度。

javascript
document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open('POST', this.action, true);

xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) 100;
document.getElementById('progressBar').style.width = percentComplete + '%';
document.getElementById('progressBar').textContent = Math.round(percentComplete) + '%';
}
};

xhr.onload = function() {
if (xhr.status === 200) {
alert('文件上传成功!');
} else {
alert('文件上传失败!');
}
};

xhr.send(formData);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var xhr2 = new XMLHttpRequest();
xhr2.open('GET', '/upload/progress', true);
xhr2.onreadystatechange = function() {
if (xhr2.readyState === 4 && xhr2.status === 200) {
var progress = JSON.parse(xhr2.responseText).progress;
document.getElementById('progressBar').style.width = progress + '%';
document.getElementById('progressBar').textContent = Math.round(progress) + '%';
}
};
xhr2.send();
}
};

xhr.send(formData);
});

总结

本文介绍了使用Python语言和Flask框架实现文件上传进度条的前端后端协同方法。通过HTML、JavaScript和Python技术,我们成功实现了文件上传进度的实时显示。在实际应用中,可以根据需求对代码进行优化和扩展。