Problem while uploading a binary file using cgi module

Jason Orendorff jason at jorendorff.com
Wed Feb 6 12:19:27 EST 2002


J. Wang writes:
> import cgi
> 
> print 'Content-type: text/html\n'
> form = cgi.FieldStorage()
> if not form:
>     [...]
> elif form.has_key("filename"):
> 	item = form["filename"]
> 	if item.file:
> 		while 1:
> 			data = item.file.readline()
> 			fp = file('1.jpg','wb')
> 			if data:
> 				fp.write(data)
> 			else:
> 				break
> 			fp.close()

Every time through the loop you are completely overwriting your file.

Do this instead:

elif form.has_key("filename"):
    item = form["filename"]
    if item.file:
        fp = file('1.jpg','wb')
        while 1:
            data = item.file.readline()
            if data:
                fp.write(data)
            else:
                break
        fp.close()

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list