67

有没有办法用 Flask 接收多个上传的文件?我尝试了以下方法:

<form method="POST" enctype="multipart/form-data" action="/upload">
  <input type="file" name="file[]" multiple="">
  <input type="submit" value="add">
</form>

然后打印以下内容request.files['file']

@app.route('/upload', methods=['POST'])
def upload():
  if not _upload_dir:
    raise ValueError('Uploads are disabled.')

  uploaded_file = flask.request.files['file']
  print uploaded_file
  media.add_for_upload(uploaded_file, _upload_dir)
  return flask.redirect(flask.url_for('_main'))

如果我上传多个文件,它只会打印集合中的第一个文件:

<FileStorage: u'test_file.mp3' ('audio/mp3')>  

有没有办法使用 Flask 的内置上传处理接收多个文件?谢谢你的帮助!

4

4 回答 4

117

您可以使用flask.request.filesgetlist方法,例如:

@app.route("/upload", methods=["POST"])
def upload():
    uploaded_files = flask.request.files.getlist("file[]")
    print uploaded_files
    return ""
于 2012-08-05T14:41:55.477 回答
23
@app.route('/upload', methods=['GET','POST'])
def upload():
    if flask.request.method == "POST":
        files = flask.request.files.getlist("file")
        for file in files:
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))

这个对我有用。

对于 UPLOAD_FOLDER,如果您需要在 app = flask.Flask( name )之后添加它

UPLOAD_FOLDER = 'static/upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
于 2019-07-26T13:00:52.593 回答
14

使用 Flask 1.0.2+:

files = request.files.getlist("images")

images键/值对的键在哪里。值是多个图像。

于 2018-09-28T15:25:20.040 回答
7

这是烧瓶版本“1.0.2”的工作解决方案:

images = request.files.to_dict() #convert multidict to dict
for image in images:     #image will be the key 
    print(images[image])        #this line will print value for the image key
    file_name = images[image].filename
    images[image].save(some_destination)

基本上,images[image] 有一个添加了保存功能的图像文件现在对数据做任何你喜欢做的事情。

于 2018-08-28T19:41:14.853 回答