mod_python 上传文件

1039阅读 0评论2012-11-20 niexining
分类:Python/Ruby

参考自:忘了~

点击(此处)折叠或打开

  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


上一篇:用matplotlib的pylab画图
下一篇:mod_python登录注销