flask的请求过程:匹配路由,形成一个http请求,然后调用视图函数,返回响应的回复,回复函数有redirect,render_template以及make_responae
在处理文件上传的过程中,首先确定路由和视图函数
@app.route('/upload',methods=['GET','POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
basedir = os.path.abspath(os.path.dirname(__file__)) # 本项目所在目录
upload_path = os.path.join(basedir,'static/uploads') # 文件所要存放的目录
# 因为filename是客户端post进来的,因此它视可以伪造的,
# 故而,应该调用工具模块
f.save(os.path.join(upload_path,secure_filename(f.filename)))
return redirect(url_for('upload'))
return render_template('upload.html')
然后,写一个文件上传的表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文件上传示例</h1>
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="file">
<input type="submit" value="Upload">
</p>
</form>
</body>
</html>
如此,即可