LoginSignup
22
19

More than 5 years have passed since last update.

Bottle(Python)で画像アップローダーを作成する方法

Last updated at Posted at 2016-06-07

Bottle To Uploader By.Python

メモ用のため、最低限の内容となっています。


各種Ver.

  • Bottle - Ver.0.13-dev
  • Python - Ver.2.7.10

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)

...以下関係ないコードのため省略

その他

外部接続も許可したかったので、runのhostは、「localhost」ではなく、
「0.0.0.0」で記載。

また、テンプレート用の画像ファイルパスも追加している。

@追記 (複数ファイルアップする場合)

myapp.py
# 以上変更無し

#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)

# 以下変更無し

更新内容のキモは、enumerateを使用したことです。
こちらを利用することで、インデックス付きの要素を付加してデータを保管できる。
※なお、本記載の内容では、同一名ファイルの考慮はしておりません。
 実際のコードでは、同一名ファイルの処理を施しております。

参照先

テンプレート参考URL

画像アップロード参考URL

複数ファイルアップの参考元となったURL

以上、最近参考にしたBottleのまとめでした。。。

22
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19