- 在Flask中处理文件上传非常简单。它需要一个HTML表单,其enctype属性设置为“multipart / form-data”,将文件发布到URL。URL处理程序从request.files[]对象中提取文件,并将其保存到所需的位置。
- 每个上传的文件首先会保存在服务器上的临时位置,然后将其实际保存到它的最终位置。目标文件的名称可以是硬编码的,也可以从request.files[file]对象的filename属性中获取。但是,建议使用secure_filename()函数获取它的安全版本。
- 可以在Flask对象的配置设置中定义默认上传文件夹的路径和上传文件的最大大小。
- ‘upload.html’有一个文件选择器按钮和一个提交按钮。
以下代码具有’/ upload’ URL规则,该规则在templates文件夹中显示’upload.html’,以及’/ upload-file’ URL规则,用于调用uploader()函数处理上传过程。
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
- flask_upload.py
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
@app.route('/upload',endpoint='upload')
#此处需加endpoint,否则报错
def upload_file():
return render_template('upload.html')
@app.route('/uploader', endpoint='uploader',methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug=True)
运行程序:http://localhost:5000/upload
选择文件后文件名会显示在选择文件按钮旁边
-
点击提交:URL变成http://localhost:5000/uploader
-
定义路由的时候没有用到endpoint参数,报错
View function mapping is overwriting an existing endpoint function: upload_file -
解决方法:
@app.route('/upload',endpoint='upload')
参考链接:添加链接描述