Ответ 1
Начиная с 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, 'w') as open_file:
open_file.write(upload.file.read())
...
- Запустить сервер;
- Введите "localhost: 8080" в своем браузере.