Flask File Upload with Real-time Progress Bar
<p>from flask import Flask, request, redirect, url_for, jsonify
import os
import threading</p>
<p>app = Flask(<strong>name</strong>)
app.config['UPLOAD_FOLDER'] = 'C://'</p>
<p>UPLOAD_PERCENTAGE = 0</p>
<p>def update_upload_percentage():
global UPLOAD_PERCENTAGE
while UPLOAD_PERCENTAGE < 100:
UPLOAD_PERCENTAGE += 1
print(f'Upload Percentage: {UPLOAD_PERCENTAGE}')
threading.Event().wait(0.1)</p>
<p>@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
global UPLOAD_PERCENTAGE
UPLOAD_PERCENTAGE = 0
file = request.files['file']
print(file)
if file:
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File uploaded successfully!'
return '''
<!doctype html>
<html>
<head>
<title>55</title>
</head>
<body>
<h1>Remote File Upload</h1>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='file'>
<input type='submit' value='Upload'>
</form>
<div id='progress'></div>
<script>
var interval = setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/progress', true);
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('progress').innerHTML = 'Upload Progress: ' + xhr.responseText + '%';
if (xhr.responseText == 100) clearInterval(interval);
}
};
xhr.send();
}, 1000);
</script>
</body>
</html>
'''</p>
<p>@app.route('/progress')
def progress():
global UPLOAD_PERCENTAGE
return jsonify(UPLOAD_PERCENTAGE)</p>
<p>if <strong>name</strong> == '<strong>main</strong>':
threading.Thread(target=update_upload_percentage).start()
app.run(debug=True)</p>
原文地址: https://www.cveoy.top/t/topic/obDr 著作权归作者所有。请勿转载和采集!