我允许连接到我的python服务器的客户端要求提供图片。我给他一个固定的http,其中包含以下代码的二进制数据(忽略错误的识别):
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
唉,我在测试时只得到一页乱码(图片的数据)。我做错了什么以及如何解决?
答案 0 :(得分:1)
您正在发送JPEG数据,但告诉您正在发送HTML的浏览器:
reply += 'Content-Type: text/html; charset=ISO-8859-1\r\n'
您应该告诉客户端您正在发送JPEG图像:
reply += 'Content-Type: image/jpg\r\n'