Uploading files with cgi - binary-files are truncated !?

dermoon dermoon at hotmail.com
Wed Oct 8 18:21:46 EDT 2003


Made this simple cgi-upload script that uses fieldstorage from a
web-form. ASCII-based files works fine, but if i try to upload
binary-files (word-documents, images) the files seems to be truncated
- e.g. an image-file that contains 3398 bytes is uploaded with only
425 bytes. Am I doing something wrong here?

Here is the code in full:

<!-- The form-->
<FORM METHOD="POST" ACTION="cgi-bin/upload.py"
enctype="multipart/form-data">
<INPUT TYPE=FILE NAME="filename" size=40>
<INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM>

#upload.py
print "Content type: text/html"
print
import cgi,sys,traceback,os


def stripPath(fpname):
    #strip off leading path and drive stuff from dos/unix/mac files
    import string
    fname = fpname
    for delim in (':','/','\\'):
        while (1):
        	p1 = string.find(fname,delim)
        	if (p1<0): break
            	fname = fname[p1+1:]
    return(fname)

try:
	form=cgi.FieldStorage()
	if form.has_key("filename"):
		fileitem=form["filename"]

		remoteFilename=fileitem.filename

		filename = stripPath(remoteFilename)

		filedata=fileitem.value		
		print len(filedata)

		localFilename = os.path.join('../', filename)
        	fstrm = open(localFilename, 'wb')
        	fstrm.write(filedata)
        	fstrm.close()
			
	else:
		print 'The form is empty!'
except:
	sys.stderr = sys.stdout
        traceback.print_exc()




More information about the Python-list mailing list