Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading multiple files via single form field via Python CGI

Tags:

python

cgi

I would like to upload multiple files using a single form field via Python CGI script using the code here. Newer browsers seem to support this feature per here and here. The HTML form seems straightforward:

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

Using this form to select two files name file0 and file1 will result in the following per HTML5 input multiple attribute:

file=file0&file=file1

I initially assumed it would be an array of sort but it seems to use an ampersand for separation.

My attempt to modify the code and add a for statement to iterate through each file specified in the form field using the following code has been unsuccessful (see error below). I am up for other ideas that may also work using Python if using a for statement is not the best route.

#!/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,)

Single file selected error:

 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

Two files selected error:

 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

If the .filename references are removed, a third error is produced, same for single or two files being selected:

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
like image 653
Astron Avatar asked Sep 09 '26 06:09

Astron


1 Answers

Remove for file in form. The error implies that form['file'] is a list.

Add to html form: 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)
like image 70
jfs Avatar answered Sep 11 '26 18:09

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!