21

HTML:

<form action="/upload" method="post" enctype="multipart/form-data">
  Category:      <input type="text" name="category" />
  Select a file: <input type="file" name="upload" />
  <input type="submit" value="Start upload" />
</form>

View:

@route('/upload', method='POST')
def do_login():
    category   = request.forms.get('category')
    upload     = request.files.get('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)
    upload.save(save_path) # appends upload.filename automatically
    return 'OK'

I'm trying to do this code but it is not working. What I'm doing wrong?

Mark Hildreth
  • 36,998
  • 9
  • 113
  • 105
William Nakagawa
  • 246
  • 1
  • 2
  • 6
  • 4
    `get_save_path_for_category` is just an example used in the Bottle documentation and not part of the Bottle API. Try setting `save_path` to `/tmp` or something. If that doesn't help: post errors... – robertklep Feb 24 '13 at 08:58
  • 2
    And: The upload.save() method is part of bottle-0.12dev which is not released yet. If you use bottle 0.11 (the latest stable release) then refer to the stable documentation. – defnull Feb 24 '13 at 15:11
  • you get this error "raise AttributeError, name AttributeError: save" ? .. – Hamoudaq Feb 27 '13 at 20:14
  • No the error is that I'm using bottle 0.11 and it doesn't support upload.save(). I just wrote a normal write file in python and that worked well. – William Nakagawa Mar 02 '13 at 18:40

1 Answers1

38

Starting from bottle-0.12 the FileUpload class was implemented with its upload.save() functionality.

Here is example for the Bottle-0.12:

import os
from bottle import route, request, static_file, run

@route('/')
def root():
    return static_file('test.html', root='.')

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

    save_path = "/tmp/{category}".format(category=category)
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    file_path = "{path}/{file}".format(path=save_path, file=upload.filename)
    upload.save(file_path)
    return "File successfully saved to '{0}'.".format(save_path)

if __name__ == '__main__':
    run(host='localhost', port=8080)

Note: os.path.splitext() function gives extension in ".<ext>" format, not "<ext>".

  • If you use version previous to Bottle-0.12, change:

    ...
    upload.save(file_path)
    ...
    

to:

    ...
    with open(file_path, 'wb') as open_file:
        open_file.write(upload.file.read())
    ...
  • Run server;
  • Type "localhost:8080" in your browser.
Stanislav
  • 806
  • 10
  • 17