点击(此处)折叠或打开
- #coding=utf-8
- import os
- def form():
- return u"""\
-
- -Type" content="text/html" charset="utf-8">
-
上传文件 -
File: " name="file">
" value="上传">
- """
- # Generator to buffer file chunks
- def fbuffer(f, chunk_size=10000):
- while True:
- chunk = f.read(chunk_size)
- if not chunk: break
- yield chunk
- def upload(req):
- # A nested FieldStorage instance holds the file
- fileitem = req.form['file']
- # Test if the file was uploaded
- if fileitem.filename:
- # strip leading path from file name to avoid directory traversal attacks
- fname = os.path.basename(fileitem.filename).decode('utf-8')
- # build absolute path to files directory
- dir_path = os.path.join(os.path.dirname(req.filename), 'files')
- f = open(os.path.join(dir_path, fname), 'wb', 10000)
- # Read the file in chunks
- for chunk in fbuffer(fileitem.file):
- f.write(chunk)
- f.close()
- message = u'文件 "%s" 上传成功!' % fname
- else:
- message = u'上传失败'
-
- return u"""\
-
- -Type" content="text/html" charset="utf-8">
-
上传文件 -
%s
- """ % message