bottle.py 實現批量文件上傳

bottle.py是python的一個Web框架,整個框架只有一個文件,幾十K,卻自帶了路徑映射、模板、簡單的數據庫訪問等web框架組件,確實是個可用的框架。初學web開發可以拿來玩玩,其語法簡單,部署也很方便。官方文檔: http://bottlepy.org/docs/dev/tutorial.html (官方文檔的介紹挺好懂的,主要是這個框架比較小)

先演示一個簡單的例子吧:

from bottle import route, run

@route('/:name')
def index(name='World'):
         return 'Hello %s!' % name

run(host='localhost', port=8080)

我準備使用bottle.py實現一個批量文件上傳的功能,但是根據官方文檔的介紹,它只提供了一個上傳一個文件的功能,文檔介紹如下:

  • FILE UPLOADS

To support file uploads, we have to change the tag a bit. First, we tell the browser to encode the form data in a different way by adding an enctype=”multipart/form-data” attribute to the tag. Then, we add tags to allow the user to select a file. Here is an example:*

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

Bottle stores file uploads in BaseRequest.files as FileUpload instances, along with some metadata about the upload. Let us assume you just want to save the file to disk:

@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 = get_save_path_for_category(category)
    upload.save(save_path) # appends upload.filename automatically
    return 'OK'
  • FileUpload. filename contains the name of the file on the clients file system, but is cleaned up and normalized to prevent bugs caused by unsupported characters or path segments in the filename. If you need the unmodified name as sent by the client, have a look at FileUpload.raw_filename.

  • The FileUpload.save method is highly recommended if you want to store the file to disk. It prevents some common errors (e.g. it does not overwrite existing files unless you tell it to) and stores the file in a memory efficient way. You can access the file object directly via FileUpload.file. Just be careful.


文檔中提供了FileUpload.filename,FileUpload.raw_filename,FileUpload.file,FileUpload.save等接口,我們可以使用FileIpload.save來保存文件到磁盤,可以使用FileIpload.file來完成讀取二進制流的任務,大家可以根據需要來完成相應的需求,下面我給出一個批量上傳圖片的例子,並以二進制流來讀取它們(讀完之後大家可以將這些數據保存到數據庫中)


#!/usr/bin/env python
from bottle import run,post,get,request

@get(r'/')
def index():
    return '''
            <!DOCTYPE html>
            <html>
            <head>
            <title>
            Solution 4-5: Sending multiple files
            </title>
            </head>
            <body>
            <form action='/up' enctype="multipart/form-data" method='post'>
            <fieldset>
            <legend>Solution 4-5: Sending multiple files</legend>
            <label>Upload one or more files:</label>
            <input type="file" name="upload" multiple />
            <input type='submit' value='submit'>
            </fieldset>
            </form>
            </body>
            </html>
            '''

@post(r'/up')
def uploadFile():
    upload = request.files.getall('upload')
    for meta in upload:
        buf = meta.file.read()
        print ('image:',str(buf))

run(host='localhost', port=8888,debug=True)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章