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

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

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

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

posted @ 2018-10-17 20:59  成民  阅读(5268)  评论(0编辑  收藏  举报