2013-02-24 34 views
11

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' 

我试图做到这一点代码,但它无法正常工作。我做错了什么?

+4

'get_save_path_for_category'只是Bottle文档中使用的一个示例,不是Bottle API的一部分。尝试将'save_path'设置为'/ tmp'或其他东西。如果这没有帮助:发布错误... – robertklep 2013-02-24 08:58:10

+2

并且:upload.save()方法是尚未发布的bottle-0.12dev的一部分。如果您使用瓶子0.11(最新的稳定版本),请参阅稳定文档。 – defnull 2013-02-24 15:11:04

+0

你得到这个错误“raise AttributeError,名称 AttributeError:save”? .. – Hamoudaq 2013-02-27 20:14:59

回答

23

瓶0.12FileUpload级开始用其upload.save()功能实现。

这里例如为瓶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>。 “格式,而不是” <转> ”。

  • 如果使用以前的版本要瓶0.12,更改:

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

到:

... 
    with open(file_path, 'w') as open_file: 
     open_file.write(upload.file.read()) 
    ... 
  • 运行服务器;
  • 在浏览器中输入“localhost:8080”。
+0

'打开(file_path,'wb')作为open_file',否则你会得到'TypeError:必须是str,而不是bytes'错误 – 2015-12-29 16:16:16