Python 如何使用瓶子框架上传和保存文件
HTML:Python 如何使用瓶子框架上传和保存文件,python,python-2.7,bottle,Python,Python 2.7,Bottle,HTML: 我试图做这个代码,但它不工作。我做错了什么?从瓶子-0.12开始类是通过其upload.save()功能实现的 以下是瓶子-0.12的示例: @route('/upload', method='POST') def do_login(): category = request.forms.get('category') upload = request.files.get('upload') name, ext = os.path.splitext
我试图做这个代码,但它不工作。我做错了什么?从瓶子-0.12开始类是通过其upload.save()功能实现的 以下是瓶子-0.12的示例:
@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'
注意:os.path.splitext()函数以“.”格式而不是“.”格式提供扩展名
- 如果您使用的是瓶-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)
- 运行服务器李>
- 在浏览器中键入“localhost:8080”
get\u save\u path\u for\u category
只是瓶子文档中使用的一个示例,而不是瓶子API的一部分。尝试将保存路径设置为/tmp
或其他设置。如果没有帮助:post errors…和:upload.save()方法是BATTLE-0.12dev的一部分,尚未发布。如果您使用瓶子0.11(最新的稳定版本),请参阅稳定文档。您会收到此错误“raise AttributeError,name AttributeError:save”。。否错误是我正在使用瓶子0.11,它不支持upload.save()。我刚刚用python编写了一个普通的写入文件,效果很好。将open(file_path,'wb')作为open_file
,否则会得到TypeError:必须是str,而不是bytes
错误
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)
...
upload.save(file_path)
...
...
with open(file_path, 'wb') as open_file:
open_file.write(upload.file.read())
...