前端上传大文件后端Python实时返回进度,前端渲染进度条,请问前后端实现代码
时间: 2024-03-08 19:50:04 浏览: 214
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传大文件并查询进度</title>
</head>
<body>
<input type="file" id="fileInput">
<button id="uploadBtn">上传</button>
<div id="progressBar"></div>
<script>
// 上传文件
function uploadFile(file) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
const formData = new FormData();
formData.append('file', file);
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const progress = event.loaded / event.total * 100;
updateProgress(progress);
}
});
xhr.send(formData);
}
// 更新进度条
function updateProgress(progress) {
const progressBar = document.getElementById('progressBar');
progressBar.style.width = `${progress}%`;
progressBar.innerText = `${progress.toFixed(2)}%`;
}
// 上传按钮点击事件
const uploadBtn = document.getElementById('uploadBtn');
uploadBtn.addEventListener('click', () => {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
uploadFile(file);
}
});
</script>
</body>
</html>
```
后端代码:
```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
file_size = request.content_length
uploaded_size = 0
with open('/path/to/save/file', 'wb') as f:
while True:
chunk = file.read(1024 * 1024) # 每次读取1MB
if not chunk:
break
f.write(chunk)
uploaded_size += len(chunk)
progress = uploaded_size / file_size * 100
yield f"data:{progress}\n\n" # 返回进度信息
return '上传完成'
if __name__ == '__main__':
app.run()
```
在这个例子中,前端通过XMLHttpRequest发送POST请求上传文件,同时监听XMLHttpRequest.upload对象的progress事件获取上传进度,并将进度显示在页面上的进度条中。
后端使用Flask框架接收上传文件,并在写入文件的过程中,使用Python的生成器函数来实时返回上传进度信息。Flask会将生成器函数的返回值当作响应的内容返回给客户端,这样前端就能够实时获取到上传进度信息,并更新进度条的显示。
阅读全文