Search code examples
pythonhttppython-2.7network-protocolsstringio

After sending image to client I get gibberish instead of picture


I allow a client which connects to my python - server to ask for a picture. I return him a fixed http which includes the binary data by the following code (ignore bad identication):

 if os.path.isfile(PICROOT + pic_name):
                with Image.open(PICROOT + pic_name) as curr_img:
                    sio = StringIO.StringIO()

                    if url[-3:] == 'jpg':
                        curr_format = 'JPEG'
                    else:
                        curr_format = url[-3:]

                    curr_img.save(sio, format=curr_format.upper())
                    content = sio.getvalue()
                    sio.close()

now = time.strftime("%c")
reply = str(version) + " " + str(status)
reply += " " + status_msg + '\r\n'
reply += 'Date:' + now + '\r\n'
reply += 'Server: Apache/2.0.52 (WindOS)\r\n'
reply += 'Accept-Ranges: bytes\r\n'
reply += 'Connection: close \r\n'
reply += 'Content-Length: '''+str(len(content))+'\r\n'
reply += 'Content-Type: text/html; charset=ISO-8859-1\r\n'
reply += '\r\n'
reply += str(content)

return reply

alas, I'm getting only a page of gibberish (the data of the picture) when testing it. What am I doing wrong and how can it be fixed?


Solution

  • You are sending JPEG data, but are telling the browser you are sending HTML:

    reply += 'Content-Type: text/html; charset=ISO-8859-1\r\n'
    

    You should tell the client you are sending a JPEG image instead:

    reply += 'Content-Type: image/jpg\r\n'