Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e Multiple file upload with flask built in uploader

Tags:

python

flask

Uploading Files in flask has been explained in the docs properly. But I was wondering if the same built-in flask file upload can be used for multiple uploads. I went through this answer but I couldn't get it done. It says "flask" not defined. Not sure if I am missing some modules to import or just I don't know to use method getlist of flask.request.files .

My form looks like:

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

and the route is like:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
    files = request.files.getlist['file[]']
    for file in files:
        if file and allowed_file(file.filename):
            #filename = secure_filename(file.filename)
            upload(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file',
                                filename=filename))

if I replace file with "file[]" will it work? I can select multiple files doing so but flask accepts and prints only one file selected and uploads only one. Looks like I am missing something silly here.

=====EDITED======

I edited above route with suggestion below.

=====ADDITION====

One more function was necessary to keep the filename iterating and saving it.

def upload(filename):
    filename = 'https://localhost/uploads/' + filename

and calling this function inside for loop above. Did the job!

Not sure if its a genuine solution but it did the trick.

like image 962
Chandan Gupta Avatar asked Mar 23 '23 02:03

Chandan Gupta


1 Answers

You'll want to call the getlist method of request.files (which is an instance of werkzeug.datastructures.MultiDict):

files = request.files.getlist('file')
for file in files:
    hande_file(file)

handle_file might be implemented like this:

def handle_file(f):
    if not allowed_file(f.filename):
        return

    filename = secure_filename(f.filename)
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)
like image 148
Sean Vieira Avatar answered Apr 02 '23 19:04

Sean Vieira