如何使用Bottle框架上传并保存文件

23 投票
1 回答
26403 浏览
提问于 2025-04-17 16:55

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>

视图:

@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'

我在尝试写这段代码,但它没有正常工作。我哪里出错了呢?

1 个回答

39

bottle-0.12开始,FileUpload类被实现了,并且它有了upload.save()这个功能。

下面是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)

注意:os.path.splitext()这个函数返回的文件扩展名是以".<ext>"的格式出现,而不是"<ext>"。

  • 如果你使用的是Bottle-0.12之前的版本,需要把:

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

改成:

    ...
    with open(file_path, 'wb') as open_file:
        open_file.write(upload.file.read())
    ...
  • 启动服务器;
  • 在浏览器中输入"localhost:8080"。

撰写回答