主程序
from flask import Flask, request, render_template
app = Flask(__name__)
# 用于存储上传文件的目录,请根据实际情况修改
UPLOAD_FOLDER = 'uploads/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def upload_form():
return render_template('upload.html')
@app.route('/', methods=['POST'])
def upload_file():
file = request.files['file']
if file:
filename = file.filename
file.save(app.config['UPLOAD_FOLDER'] + filename)
return f'文件 "{filename}" 上传成功!'
else:
return '没有选择文件'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) # 这里设置为监听所有IP,以便手机在同一网络下可以访问
upload.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传带进度</title>
<style>
#progress-bar {
width: 100%;
background-color: #f3f3f3;
border-radius: 5px;
}
#progress-bar div {
height: 30px;
background-color: #4CAF50;
width: 0%;
text-align: center;
line-height: 30px;
color: white;
transition: width 0.5s;
}
</style>
</head>
<body>
<h1>上传文件并显示进度</h1>
<form method=post id="upload-form" enctype="multipart/form-data">
<input type="file" name="file" id="file-input">
<button type="submit">上传</button>
</form>
<div id="progress-bar">
<div></div>
</div>
<script>
document.getElementById('upload-form').addEventListener('submit', function(e) {
var form = new FormData(this);
var xhr = new XMLHttpRequest();
var progressBar = document.querySelector('#progress-bar div');
xhr.open('POST', '/', true);
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
progressBar.style.width = percentComplete + '%';
progressBar.textContent = Math.round(percentComplete) + '%';
}
});
xhr.onloadstart = function() {
progressBar.style.width = '0%';
progressBar.textContent = '0%';
};
xhr.onloadend = function() {
if (xhr.status === 200) {
alert('上传成功');
} else {
alert('上传失败');
}
};
xhr.send(form);
});
</script>
</body>
</html>
文件结构
程序挺好玩也比较实用,方便手机直接将数据上传至电脑。