How to upload and save a file using bottle framework

社会主义新天地 提交于 2019-12-02 17:38:27

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!