Keir
Keir

Reputation: 607

Python Bottle multiple file upload

I wish to upload multiple files to a Bottle server.

Single file upload works well and by modifying the HTML input tag to be "multiple", the browse button allows the selection of multiple files. The upload request handler only loads the last file. How can I get all the files uploaded in one go?

The code I am experimenting with:

    from bottle import route, request, run

    import os

    @route('/fileselect')
    def fileselect():
        return '''
    <form action="/upload" method="post" enctype="multipart/form-data">
      Category:      <input type="text" name="category" />
      Select a file: <input type="file" name="upload" multiple />
      <input type="submit" value="Start upload" />
    </form>
        '''

    @route('/upload', method='POST')
    def do_upload():
        category   = request.forms.get('category')
        upload     = request.files.get('upload')
        print dir(upload)
        name, ext = os.path.splitext(upload.filename)
        if ext not in ('.png','.jpg','.jpeg'):
            return 'File extension not allowed.'

        #save_path = get_save_path_for_category(category)
        save_path = "/home/user/bottlefiles"
        upload.save(save_path) # appends upload.filename automatically
        return 'OK'

    run(host='localhost', port=8080)

Upvotes: 6

Views: 3517

Answers (1)

approxiblue
approxiblue

Reputation: 7122

mata's suggestion works. You can get the list of uploaded files by calling getall() on request.files.

@route('/upload', method='POST')
def do_upload():
    uploads = request.files.getall('upload')
    for upload in uploads:
        print upload.filename
    return "Found {0} files, did nothing.".format(len(uploads))

Upvotes: 5

Related Questions