如何使用瓶子框架上传和保存文件

时间:2013-02-24 08:40:22

标签: python python-2.7 bottle

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 个答案:

答案 0 :(得分:28)

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()函数在&#34;。&lt; ext&gt;&#34;中提供扩展名。格式,而不是&#34;&lt; ext&gt;&#34;。

  • 如果您使用 Bottle-0.12 之前的版本,请更改:

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

为:

    ...
    with open(file_path, 'wb') as open_file:
        open_file.write(upload.file.read())
    ...
  • 运行服务器;
  • Type&#34; localhost:8080&#34;在您的浏览器中。