[英]python UnicodeDecodeError of POST method
Main.py code: main.py 代码:
self.cropped.save(os.environ['TEMP']+'\\BFCP.SCRSH.TEMP.png',format='PNG')
file = open(os.environ['TEMP']+'\\BFCP.SCRSH.TEMP.png','rb')
files = {sd: file.read()}
file.close()
rs = requests.post('http://192.168.1.48:8000', files=files)
sd - image code (5dfghr7efh) Here I want to send PIL.image (self.cropped.save) to server by post method. sd - 图像代码 (5dfghr7efh) 在这里我想通过 post 方法将 PIL.image (self.cropped.save) 发送到服务器。 server.py code:
server.py 代码:
import socket
client_socket,adress = server.accept()
print('Accepted')
data = client_socket.recv(2048)
f = open('code','wb')
f.write(data)
f.close()
data = data.decode('utf-8')
print(client_socket, adress,data)
Main.py error: Main.py 错误:
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
server.py error: server.py 错误:
Traceback (most recent call last):
File "server.py", line 75, in <module>
start()
File "server.py", line 21, in start
data = data.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 363: invalid start byte
What's wrong with my code ?我的代码有什么问题?
decode()
is for text files but you send image. decode()
用于文本文件,但您发送图像。
Don't use decode()
for images, audio files, movies, excel files, PDF, etc.不要对图像、音频文件、电影、excel 文件、PDF 等使用
decode()
。
You may get only headers
(all before empty line \\n\\n
) and decode headers
您可能只获得
headers
(都在空行\\n\\n
)并解码headers
but rest ( body
with form
data) display without decoding.但其余(带有
form
数据的body
)显示而无需解码。
headers, body = data.split(b'\n\n')
headers = headers.decode('utf-8')
print(headers)
print(body)
Eventually you should split body
into parts image info
, image data
using also \\n\\n
and decode info
but not data
.最终,你应该分裂
body
分成部分image info
, image data
还使用\\n\\n
和解码info
,但没有data
。 And then you may save data
as image.png
.然后你可以将
data
保存为image.png
。
It shows that using socket
may need a lot of work and it may be simpler to use module http
to create server.这表明使用
socket
可能需要很多工作,使用模块http
创建服务器可能更简单。 OR event simpler can be use web frameworks like flask
to run server.或者更简单的事件可以使用像
flask
这样的Web框架来运行服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.