1

I am trying to upload multiple files using HTML into my flask application. I have used an html form below

<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>

and the files are being read in an Flask package as

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

when I tested this and I only upload a single file this runs fine but when I upload both the files I can see that the request.files field is empty.

I is not possible to upload multiple files into flask from one form ?

tj89
  • 3,953
  • 2
  • 12
  • 12

2 Answers2

1

You have to use, getlist

@app.route('/process_data', methods=["POST"])
def process_data():
   uploaded_files = request.files.getlist("file[]")
   print uploaded_files
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • Hi Rahul, this works but now I can see inconsistent behavior sometime the uploaded_files variable has the files fed while other times its just blank . Can get hold of the reason. – tj89 May 25 '17 at 07:46
0

Actually, the request.files is not empty, it will be ImmutableMultiDict like this:

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

You can convert it to dictionary with :

dict(request.files)

Then it will be:

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

Then you can access the file1 and file2 from here.

If you want to upload multiple files, suggest this answer will be more clear for you, but you have to change your html with:

<input type="file" name="file[]" multiple="">
Tiny.D
  • 6,466
  • 2
  • 15
  • 20