Computer_Engineer
Computer_Engineer

Reputation: 403

Reading uploaded zip file

How can i read the fileitems in zip file that uploaded using form in html and using Cgi, i tried as this:

form = cgi.FieldStorage() 
file_upload = form['file']
if zipfile.is_zipfile(file_upload.filename):
    print "%s is a valid pkzip file" % file_upload.filename
else:
    print "%s is not a valid pkzip file" % file_upload.filename
zfile=zipfile.ZipFile(file_upload.filename,"r")
files_zip=zfile.namelist()

For example when i upload (test.zip)the error is No such file or directory: 'test.zip',and if i run the code without this zfile=zipfile.ZipFile(file_upload.filename,"r"), i get that test.zip is not a valid pkzip file. Thanks in advance.

Upvotes: 1

Views: 1971

Answers (1)

jfs
jfs

Reputation: 414245

You could try to pass file_upload.file to ZipFile instead of file_upload.filename.

Here's a script that prints the list of files in the zip file:

import sys
sys.stderr = sys.stdout
print "Content-Type: text/plain"
print

import cgi
import zipfile

form = cgi.FieldStorage()

filefield = form['somefile']
print "Filename:", filefield.filename

if filefield.file is not None and zipfile.is_zipfile(filefield.file):
    zfile = zipfile.ZipFile(filefield.file)
    print "Name list:\n\t",
    print "\n\t".join(zfile.namelist())

And the corresponding html form:

<!DOCTYPE html>
<form enctype="multipart/form-data" action="file-upload" method=post>
<p><label for=somefile>File: <input type=file name=somefile>
<p><input type=submit>
</form>

Upvotes: 3

Related Questions