首先要在网页 hello_form.hmtl 里面写上 form表单, 刷新后网页会出现上传文件的入口, 这样就完成了前端的部分,代码是在ex51添加的,
{% extends 'layout.html' %}
{% block content %}
<h1>Fill Out This Form from hello_form.html</h1>
<form action="/hello" method="POST" enctype="multipart/form-data">
A Greet from hello_form post <input type="text" name="greet">
<br>
Your Name from hello_form post <input type="text" name="name">
<br>
<br>
<input type="submit">
</form>
<form action="/upload" method="post" enctype="multipart/form-data">
# form表单结合input,在网页上显示上传文件入口,
Update files <input type="file" name="files">
<input type="submit"> # 提交按钮别忘记了
</form>
{% endblock %}
下面来写flask后端的app.py文件,也是在ex51 文件添加的.单独写了一个路由 /upload
import os
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/hello", methods=['POST','GET'])
def index():
greeting = 'Hello World'
if request.method == 'POST':
name = request.form['name']
greet = request.form['greet']
# print('走的if', request.method)
greeting = f"{greet}, {name}"
return render_template("index.html", greeting=greeting)
else:
# print('走的else', request.method)
return render_template("hello_form.html")
@app.route('/upload', methods=['POST', 'GET'])
def save_files():
if request.method == 'POST':
up_files = request.files['files'] #拿到前台的文件流,指明了files,要与前台一致
print('上传文件对象已经获取成功')
save_folder = 'uploadfiles' #指定上传保存到这个文件夹内
file_dir = os.path.join(os.getcwd(), save_folder) #整合保存路径
file_path = os.path.join(file_dir, up_files.filename)#用.filename拿到文件名并整合路径
up_files.save(file_path) #保存前台上传的文件
print('保存成功', up_files.filename)
else:
print(" wrong ")
return "done"
if __name__ == "__main__":
app.run()
这样就完成了,前台网页上传文件, 后台存储过程.
下面是网页截图