flask通过form表单一次上传多个文件

时间:2022-11-25 08:04:13

基本上,用了flask官网的示例代码(中文版英文版),稍微做了修改。

 import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
 def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
for file in request.files.getlist('file'): # 这里改动以存储多份文件
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''

这样就可以一次性提交多份文件。具体实现可参看相关源码