fileupload error!
penguin
penguin at bredband.no
Wed Jun 12 20:08:59 EDT 2002
Hi I try to upload a picture with a python cgi script. Tried many versions of the code, this is the current.
Here's the code and error!
The error:
Traceback (most recent call last): File "C:\cgi-bin\upload.py", line 179,
in ? xmldokument = skjema['dok'].value File "C:\Python22\lib\cgi.py", line
550, in __getitem__ raise KeyError, key KeyError: dok
The code:
#!c:\python22\python.exe
# FileTransfer.py - CGI file transfer, may require Python 1.5 or higher
# Author: JeffBauer at bigfoot.com
# Prior art: Aaron Watters, Jim Fulton
import xml.dom
import xml.dom.minidom
import xml.parsers
import os, sys, traceback
import httplib
import tempfile
from whrandom import randint
from string import joinfields
from time import time
import cgi
test = 0
FileUploadRequestException="Dette gikk ikke :"
def parseDok(xmlstreng):
s=[]
pars = xml.dom.minidom.parseString(xmlstreng)
elementene = pars.getElementsByTagName('element')
for element in elementene:
ss={}
ss['dataid'] =
element.getAttribute('dataid').encode('iso_8859_1')
ss['type'] =
element.getAttribute('type').encode('iso_8859_1')
ss['format'] =
element.getAttribute('format').encode('iso_8859_1')
s += [ss]
return s
def lagFilblokk(elementliste,xmldokument):
#path = "http://192.168.0.32/upload/"
path = "http://192.168.0.32/upload/"
#path = "O:\\"
#Ting skal vist hete userfile og attach1 o.s.v.
s = [{'fieldname':'userfile','filename':xmldokument}]
att = 0
for element in elementliste:
att += 1
ss={}
ss['fieldname'] = "attach%s" % att
ss['filename'] = path + element['dataid'] +
filending(element['type'],element['format'])
s += [ss]
return s
def filending(type,format):
#Dette skal gjøres bedre
if format == 'jpeg':
return '.jpg'
if format == 'jpg':
return '.jpg'
return '.txt'
class FileUploadRequest:
"""
File upload modul, og sender en liste filer, i med gitte feltnavn.
"""
def __init__(self, uri, host, port):
self.uri = uri
self.host = host
self.port = port
self.queryString = ''
self.teller = 1
#self.boundary= '%s%s_%s' % ('-tr--', int(time()), randint(1,10000))
self.boundary= '%s%s_%s' % ('rrrr', time(), randint(1,10000))
#print self.boundary
def load(self, filenames, headerDict=None):
for filename in filenames:
if not '?' in filename['filename']:
#Dette er ikke et xml dokument (som jo begynner med
<?xml...
f = open(filename['filename'],'rb')
data = f.read(1000000)
#Problem her kanskje
f.close()
else:
#Det er ikke noe filnavn dataene
data = filename['filename']
filename['filename'] = 'test.xml'
hdr = []; part = []; total = []
hdr.append('Content-Disposition: form-data; name="%s";
filename="%s"' % (filename['fieldname'],filename['filename']))
hdr.append('Content-Type: application/octet-stream')
hdr.append('Content-Length: %d' % len(data))
# Add user-defined header values here, if provided.
# Reminder: FieldStorage will convert key to lowercase.
if type(headerDict) == type({}):
for k in headerDict.keys():
hdr.append("%s: %s", (k, headerDict[k]))
part.append("%s\n\n%s" % (joinfields(hdr,'\n'), data))
total.append('--%s\n' % self.boundary)
total.append(joinfields(part, "\n--%s\n" % self.boundary))
#total.append('\n--%s--\n' % self.boundary)
#print joinfields(total, '')
self.queryString += joinfields(total, '')
self.teller +=1
self.queryString +=('\n--%s--\n' % self.boundary) #Dette er
sluttmarkeringen
def request(self):
query = self.queryString
contentType = 'multipart/form-data; boundary=%s' % self.boundary
contentLength = str(len(query))
h = httplib.HTTP()
h.connect(self.host, self.port)
h.putrequest('POST', self.uri)
h.putheader('Accept', '*/*')
h.putheader('Proxy-Connection', 'Keep-Alive')
h.putheader('User-Agent', 'Glue0.1 [no] (Mac OSX; U)')
h.putheader('Content-Type', contentType)
h.putheader('Content-Length', contentLength)
h.endheaders()
h.send(query)
rcode, rmsg, headers = h.getreply()
response = h.getfile().read(10000)
"""
if rcode != 200:
msg = "error: %s, %s\n%s %s" % (rcode, self.uri, rmsg, response)
raise FileUploadRequestException(msg)
"""
f=file('c:\\RESPONSE.html','w')
f.write(response)
f.close
##
f=file('c:\\qvery.txt','w')
f.write(query)
f.close
##
return response
return response
def lastoppListe(host,uri,filenames):
port = 9091
port = 8080
#port = 80
fileUploadRequest = FileUploadRequest(uri, host, port)
fileUploadRequest.load(filenames)
response = fileUploadRequest.request()
return response
def lesFil(filNavn):
r = open(filNavn)
dok = r.read(19000)
r.close()
return dok
def main(self,xmldokument):
#Først finne hvilke elementer vi har å jobbe med
elementliste = parseDok(xmldokument)
filliste = lagFilblokk(elementliste,xmldokument)
#Denne returnerer en liste over dataposter
#print filliste
svar = lastoppListe('192.168.0.1','/files/upload',filliste)
print svar
if __name__ == '__main__':
print "Content-type: text/html"
print
if test:
xmldokument = lesFil('test.xml')
else:
skjema = cgi.FieldStorage()
xmldokument = skjema['dok'].value
alfa= main(None, xmldokument)
Regards stan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20020613/386bf1e4/attachment.html>
More information about the Python-list
mailing list