通过Python CGI通过单个表单字段上传多个文件

时间:2012-09-02 22:28:06

标签: python cgi

我想使用代码here通过Python CGI脚本使用单个表单字段上传多个文件。较新的浏览器似乎每herehere支持此功能。 HTML表单似乎很简单:

<input name="file" type="file" multiple="" />

使用此表单选择两个文件名file0file1,每个HTML5 input multiple attribute会生成以下内容:

file=file0&file=file1

我最初假设它将是一个排序数组,但它似乎使用&符号进行分离。

我尝试修改代码并添加for语句以使用以下代码遍历表单字段中指定的每个文件,但是未成功(请参阅下面的错误)。如果使用for语句不是最好的路径,那么我可以使用其他可能也可以使用Python的想法。

#!/usr/bin/python
import cgi, os

form = cgi.FieldStorage()

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

for fileitem in form['file']:

   # A nested FieldStorage instance holds the file
   fileitem = form['file']

   # Test if the file was uploaded
   if fileitem.filename:

      # strip leading path from file name to avoid directory traversal attacks
      fn = os.path.basename(fileitem.filename)
      f = open('/var/www/domain.com/files' + fn, 'wb', 10000)

      # Read the file in chunks
      for chunk in fbuffer(fileitem.file):
         f.write(chunk)
      f.close()
      message = 'The file "' + fn + '" was uploaded successfully'

   else:
      message = 'No file was uploaded'

   print """\
   Content-Type: text/html\n
   <html><body>
   <p>%s</p>
   </body></html>
   """ % (message,)

单个文件选择错误:

 Traceback (most recent call last):, referer: https://www.domain.com/files/upload.htm
   File "/usr/lib/cgi-bin/test.py", line 13, in <module>, referer: https://www.domain.com/files/upload.htm
     for fileitem in form['file']:, referer: https://www.domain.com/files/upload.htm
   File "/usr/lib/python2.6/cgi.py", line 518, in __iter__, referer: https://www.domain.com/files/upload.htm
     return iter(self.keys()), referer: https://www.domain.com/files/upload.htm
   File "/usr/lib/python2.6/cgi.py", line 583, in keys, referer: https://www.domain.com/files/upload.htm
     raise TypeError, "not indexable", referer: https://www.domain.com/files/upload.htm
 TypeError: not indexable, referer: https://www.domain.com/files/upload.htm
 Premature end of script headers: test.py, referer: https://www.domain.com/files/upload.htm

选择了两个文件错误:

 Traceback (most recent call last):, referer: https://www.domain.com/files/upload.htm
   File "/usr/lib/cgi-bin/test.py", line 19, in <module>, referer: https://www.domain.com/files/upload.htm
     if fileitem.filename:, referer: https://www.domain.com/files/upload.htm
 AttributeError: 'list' object has no attribute 'filename', referer: https://www.domain.com/files/upload.htm
 Premature end of script headers: test.py, referer: https://www.domain.com/files/upload.htm

如果删除了.filename引用,则会产生第三个错误,对于选择的单个或两个文件也是如此:

Traceback (most recent call last):, referer: https://www.domain.com/files/upload.htm
   File "/usr/lib/cgi-bin/test.py", line 24, in <module>, referer: https://www.domain.com/files/upload.htm
     fn = os.path.basename(fileitem), referer: https://www.domain.com/files/upload.htm
   File "/usr/lib/python2.6/posixpath.py", line 111, in basename, referer: https://www.domain.com/files/upload.htm
     i = p.rfind('/') + 1, referer: https://www.domain.com/files/upload.htm
 AttributeError: 'list' object has no attribute 'rfind', referer: https://www.domain.com/files/upload.htm
 Premature end of script headers: test.py, referer: https://www.domain.com/files/upload.htm

2 个答案:

答案 0 :(得分:2)

删除for file in form。该错误意味着form['file']是一个列表。

添加到html表单:method=post enctype=multipart/form-data

import shutil

if 'file' in form:
   filefield = form['file']
   if not isinstance(filefield, list):
      filefield = [filefield]

   for fileitem in filefield:
       if fileitem.filename:
          fn = secure_filename(fileitem.filename)
          # save file
          with open('/var/www/domain.com/files/' + fn, 'wb') as f:
              shutil.copyfileobj(fileitem.file, f)

答案 1 :(得分:0)

我不知道cgi库是否支持上传多个文件,但是你的错误很简单:你在HTML中调用了你的字段file[],但在Python中你只是简称{{1 }}。他们不一样。我建议简单地删除PHP-ism并仅调用file字段。