1

我正在尝试使用 HTML 将多个文件上传到我的烧瓶应用程序中。我在下面使用了一个 html 表单

<form action="url", method="POST", enctype="multipart/form-data">
      <font size="2">
        File2: <input type=file name=file1><br/>
        File1: <input type=file name=file2><br/>
      </font>
      <input type="submit" value="Submit">
      <input type="reset" value="Reset">
    </form>

并且文件在 Flask 包中被读取为

@app.route('/process_data', methods=["POST"])
def process_data():
    print request.files

当我对此进行测试并且只上传一个文件时,它运行良好,但是当我上传两个文件时,我可以看到 request.files 字段为空。

我不能从一种形式将多个文件上传到烧瓶中吗?

4

2 回答 2

1

你必须使用,getlist

@app.route('/process_data', methods=["POST"])
def process_data():
   uploaded_files = request.files.getlist("file[]")
   print uploaded_files
于 2017-05-24T12:45:45.383 回答
0

实际上,request.files不是空的,它会是ImmutableMultiDict这样的:

ImmutableMultiDict([('file1', <FileStorage: 'test1.jpg' ('image/jpeg')>),  ('file2', <FileStorage: 'test222.jpeg' ('image/jpeg')>)])

您可以使用以下命令将其转换为字典:

dict(request.files)

那么它将是:

{'file1': [<FileStorage: 'test1.jpg' ('image/jpeg')>], 'file2': [<FileStorage: 'test222.jpeg' ('image/jpeg')>]}

然后你可以从这里访问file1and 。file2

如果你想上传多个文件,建议这个答案对你来说会更清楚,但你必须改变你的html:

<input type="file" name="file[]" multiple="">
于 2017-05-24T12:46:19.343 回答