Chinaunix首页 | 论坛 | 博客
  • 博客访问: 153966
  • 博文数量: 33
  • 博客积分: 2057
  • 博客等级: 大尉
  • 技术积分: 430
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-19 16:37
文章分类
文章存档

2013年(2)

2012年(23)

2011年(8)

分类: Python/Ruby

2012-11-20 20:44:28

参考自:忘了~

点击(此处)折叠或打开

  1. #coding=utf-8

  2. import os

  3. def form():
  4.    return u"""\

  5.         
  6.         -Type" content="text/html" charset="utf-8">
  7.         上传文件
  8.     

  9. /form-data" action="./upload" method="post">
  10. File: " name="file">


  11. " value="上传">




  12. """

  13. # Generator to buffer file chunks
  14. def fbuffer(f, chunk_size=10000):
  15.    while True:
  16.       chunk = f.read(chunk_size)
  17.       if not chunk: break
  18.       yield chunk

  19. def upload(req):
  20.    # A nested FieldStorage instance holds the file
  21.    fileitem = req.form['file']
  22.    # Test if the file was uploaded
  23.    if fileitem.filename:
  24.       # strip leading path from file name to avoid directory traversal attacks
  25.       fname = os.path.basename(fileitem.filename).decode('utf-8')
  26.       # build absolute path to files directory
  27.       dir_path = os.path.join(os.path.dirname(req.filename), 'files')
  28.       f = open(os.path.join(dir_path, fname), 'wb', 10000)

  29.       # Read the file in chunks
  30.       for chunk in fbuffer(fileitem.file):
  31.          f.write(chunk)
  32.       f.close()
  33.       message = u'文件 "%s" 上传成功!' % fname

  34.    else:
  35.       message = u'上传失败'
  36.   
  37.    return u"""\

  38.         
  39.         -Type" content="text/html" charset="utf-8">
  40.         上传文件
  41.     

  42. %s


  43. ./form">再上传一个文件



  44. """ % message


阅读(955) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~