views:

32

answers:

0

It seems like this answer has been provided a bunch of times but in all of it, I'm still getting errors from the server and I'm sure it has to do with my code. I've tried HTTP, and HTTPConnection from httplib and both create quite different terminal outputs in terms of formatting/encoding so I'm not sure where the problem lies. Does anything stand out here? Or is there just a better way?

Pieced together from an ancient article because I really needed to understand the basis of creating the post: http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/

Note, the jpeg is supposed to be "unformatted". The pseudocode:

boundary = "somerandomsetofchars"
BOUNDARY = '--' + boundary
CRLF = '\r\n'

fields = [('aspecialkey','thevalueofthekey')]
files = [('Image.Data','mypicture.jpg','/users/home/me/mypicture.jpg')]

bodylines = []

for (key, value) in fields:
    bodylines.append(BOUNDARY)
    bodylines.append('Content-Disposition: form-data; name="%s"' % key)
    bodylines.append('')
    bodylines.append(value)

for (key, filename, fileloc) in files:
    bodylines.append(BOUNDARY)
    bodylines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
    bodylines.append('Content-Type: %s' % self.get_content_type(fileloc))
    bodylines.append('')
    bodylines.append(open(fileloc,'rb').read())
    #bodylines.append(open(fileloc,'r').read())

bodylines.append(BOUNDARY + '--')
bodylines.append('')
#print bodylines
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
body = CRLF.join(bodylines)

#conn = httplib.HTTP("www.ahost.com")   #  In both this and below, the file part was garbling the rest of the body?!?
conn = httplib.HTTPConnection("www.ahost.com")

conn.putrequest('POST', "/myuploadlocation/uploadimage")
headers = {
    'content-length': str(len(body)),
    'Content-Type' : content_type,
    'User-Agent' : 'myagent'
}
for headerkey in headers:
    conn.putheader(headerkey, headers[headerkey])
conn.endheaders()
conn.send(body)

response = conn.getresponse()
result = response.read()
responseheaders = response.getheaders()

It's interesting in that the real code I've implemented seems to work and is getting back valid responses, but the problem it it's telling me that it can't find the image data. Maybe this is particular to the server, but I'm just trying to rule out that I'm not doing some thing exceptionally stupid here. Or perhaps there's other methodologies for doing this more efficiently. I've not tried poster yet because I want to make sure I'm formatting the POST correctly first. I figure I can upgrade to poster after it's working yes?