python bottle 上传文件_bottle.py 实现批量文件上传

本文介绍了Python的轻量级Web框架Bottle,展示了如何通过Bottle实现批量文件上传。文章首先解释了Bottle的基础知识,然后详细说明了如何修改HTML表单以支持文件上传,并提供了如何处理上传文件的代码示例,包括使用FileUpload对象的save方法来保存文件到磁盘以及读取二进制流。最后,给出了一个批量上传图片的完整示例,读取上传的二进制流数据。
摘要由CSDN通过智能技术生成

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

Category:

Select a file:

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

Solution 4-5: Sending multiple files

Solution 4-5: Sending multiple files

Upload one or more files:

'''

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值