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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章