前端代码 Demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tbody>
<tr>
<td>头像:</td>
<td><input type="file" name="avatar"></td>
</tr>
<tr>
<td>描述:</td>
<td><input type="text" name="desc"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="点击提交"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
后端代码
from flask import Flask, request, render_template
import time
app = Flask(__name__)
@app.route(‘/upload‘, methods=[‘GET‘, ‘POST‘])
def upload():
if request.method == "GET":
return render_template(‘Demo.html‘)
if request.method == ‘POST‘:
desc = request.form.get(‘desc‘) # 获取描述信息
avatar = request.files.get(‘avatar‘) # 获取文件:request.files
avatar.save(‘%s.png‘ % time.time()) # 保存文件
return ‘文件上传成功‘
if __name__ == ‘__main__‘:
app.run(host=‘127.0.0.1‘, port=‘8080‘, debug=True)
06-flask-文件上传案例