基于 Bottle 的文件上传脚本

该脚本实在是简陋哈,只能上传文件和下载文件,显示当前服务器上的文件列表,没有其它的功能,只是自己学习 Bottle 的练习了:

#!/usr/bin/env python
# encoding: utf-8
"""
File: com.costony.fileuploader.py
Created by Pan Tao on 2011-09-20.
Copyright (c) 2011 CosTony.Com. All rights reserved.
"""
from bottle import route, template, run, request, redirect, static_file
import os
index_tpl = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>COS TONY FILE UPLOADER</title>
    <style type="text/css">
    body {font-family: arial; font-size: 80%;line-height:2em;}
    a {color: #393; font-size:1.5em; text-decoration:none}
    h1 { font-size:2em; padding-bottom: .3em;border-bottom: 1px solid #999;}
    </style>
</head>
<body>
<h1>Upload File</h2>
<form action = "/upload" method = "POST" enctype="multipart/form-data">
<input type="file" name="data" />
<input type="submit" value="Upload" />
</form>
<h1>Files List</h1>
<ul>
%for file in files:
<li><a href="/download/{{file}}">{{file}}</a></li>
%end
</ul>
</body>
</html>
'''
@route('/')
def index():
return template(index_tpl, files = [f for f in os.listdir('./files') if not f.startswith('.')])
@route('/upload', method = 'POST')
def upload():
data = request.files.get('data')
save_file = open('./files/{}'.format(data.filename), 'wb')
if data.file:
try:
buf = data.file.read(data.bufsize)
while buf:
save_file.write(buf)
buf = data.file.read(data.bufsize)
save_file.close()
return redirect('/')
except Exception, e:
return redirect('/')
@route('/download/:filename')
def download(filename):
return static_file(filename, root='./files')
if __name__ == '__main__':
    run(reloader = True)

标签: none

评论已关闭