Python 如何使用 Bottle 框架上传和保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15050064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload and save a file using bottle framework
提问by William Nakagawa
HTML:
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?
我正在尝试执行此代码,但它不起作用。我做错了什么?
回答by Stanislav
Starting from bottle-0.12the FileUploadclass was implemented with its upload.save()functionality.
从开始瓶0.12的文件上传类用它实现upload.save()功能。
Here is example for the Bottle-0.12:
这是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>".
注意:os.path.splitext()函数以“.<ext>”格式给出扩展名,而不是“<ext>”。
If you use version previous to Bottle-0.12, change:
... upload.save(file_path) ...
如果您使用Bottle-0.12之前的版本,请更改:
... 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.
- 运行服务器;
- 在浏览器中输入“localhost:8080”。

