Bottle To Uploader By.Python
It is for memos, so it is the minimum content.
myapp.py
from bottle import route, run, template, request, static_file, url, get, post, response, error, abort, redirect, os
import sys, codecs
import bottle.ext.sqlalchemy
import sqlalchemy
import sqlalchemy.ext.declarative
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
@route("/")
def html_index():
return template("index", url=url)
@route("/static/<filepath:path>", name="static_file")
def static(filepath):
return static_file(filepath, root="./static")
@route("/static/img/<img_filepath:path>", name="static_img")
def static_img(img_filepath):
return static_img(img_filepath, root="./static/img/")
#File Upload
@get('/upload')
def upload():
return '''
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="submit" value="Upload"></br>
<input type="file" name="upload"></br>
</form>
'''
@route('/upload', method='POST')
def do_upload():
upload = request.files.get('upload', '')
if not upload.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
return 'File extension not allowed!'
save_path = get_save_path()
upload.save(save_path)
return 'Upload OK. FilePath: %s%s' % (save_path, upload.filename)
def get_save_path():
path_dir = "./static/img/"
return path_dir
run(host="0.0.0.0", port=8000, debug=True, reloader=True)
...Omitted because the code is not relevant below
I also wanted to allow external connections, so the run host is not "localhost" Described as "0.0.0.0".
It also adds an image file path for the template.
myapp.py
#No change
#File Upload
@get('/upload')
def upload():
return '''
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="submit" value="Upload"></br>
- <input type="file" name="upload"></br>
+ <input multiple="multiple" name="upload[image_file_name][]" type="file" accept="image/*" id="upload">
</form>
'''
@route('/upload', method='POST')
def do_upload():
- upload = request.files.get('upload', '')
+ pload_files = request.files.getall('upload[image_file_name][]')
- if not upload.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
- return 'File extension not allowed!'
- save_path = get_save_path()
- upload.save(save_path)
- return 'Upload OK. FilePath: %s%s' % (save_path, upload.filename)
+ save_path = get_save_path()
+ for count, uplad_file in enumerate(upload_files):
+ upload_img = uplad_file
+ if not upload_img.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
+ return template("no {{uplad_file}}", uplad_file=uplad_file)
+ upload_img.save(save_path)
+ return 'Upload OK. FilePath: %s ImageFiles:%s' % (save_path, pload_files)
#No change below
The key to the update is the use of ʻenumerate`. By using this, you can add indexed elements and store data.
-Generating static file links with Python's Bottle framework
-Convenient zip, enumerate function in for loop -enumerate (iterable, start = 0) (official)
The above is a summary of Bottle that I recently referred to. .. ..
Recommended Posts