Uploading multiple files with Flask

PythonFile UploadFlask

Python Problem Overview


Is there a way to receive multiple uploaded files with Flask? I've tried the following:

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

And then printed the contents of 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'))

If I upload multiple files, it only prints the first file in the set:

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

Is there a way to receive multiple files using Flask's built-in upload handling? Thanks for any help!

Python Solutions


Solution 1 - Python

You can use method getlist of flask.request.files, for example:

@app.route("/upload", methods=["POST"])
def upload():
    uploaded_files = flask.request.files.getlist("file[]")
    print uploaded_files
    return ""

Solution 2 - Python

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

It works for me.

for UPLOAD_FOLDER if you need add this just after app = flask.Flask(name)

UPLOAD_FOLDER = 'static/upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

Solution 3 - Python

Using Flask 1.0.2+:

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

Where images is the key of the key/value pair. With the Value being the multiple images.

Solution 4 - Python

this is a working solution for flask version '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)

basically, images[image] has an image file with save function added to it Now do whatever you like to do with the data.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaldean BrownView Question on Stackoverflow
Solution 1 - PythonFedor GogolevView Answer on Stackoverflow
Solution 2 - PythonJulienView Answer on Stackoverflow
Solution 3 - PythonJackView Answer on Stackoverflow
Solution 4 - PythonSATYAJEET RANJANView Answer on Stackoverflow