Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Bottle multiple file upload

Tags:

python

bottle

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)
like image 329
Keir Avatar asked Jul 26 '15 22:07

Keir


People also ask

How do you upload multiple files in Python?

Run the Application by running “python multiplefilesupload.py”. Go to browser and type “http://localhost:5000”, you will see “upload files” in browser.

How do I post multiple pictures on flask?

On the UI (User Interface) there is an input field which is used to select multiple files. To select multiple files after clicking on browse button you need to hold Ctrl key (Windows OS) on the keyboard and click on the images you want to select for upload.


1 Answers

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))
like image 175
approxiblue Avatar answered Oct 16 '22 18:10

approxiblue