Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading multiple files with Flask

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!

like image 875
Haldean Brown Avatar asked Aug 05 '12 14:08

Haldean Brown


People also ask

How do I upload files to Flask?

Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.


2 Answers

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 "" 
like image 72
Fedor Gogolev Avatar answered Nov 15 '22 23:11

Fedor Gogolev


@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 
like image 40
Julien Avatar answered Nov 15 '22 21:11

Julien