【发布时间】:2018-11-12 12:55:02
【问题描述】:
是否可以通过套接字发送包含文件(图像或文档)作为值的字典?
我尝试了类似下面的方法但我失败了..
with open("cat.jpeg", "rb") as f:
myFile = f.read(2048)
data = {"id": "1283", "filename": "cat.jpeg", "file": myFile}
dataToSend = json.dumps(data).encode("utf-8")
这给出了一个 json 错误,myFile 是一个字节数组,无法序列化。
我尝试使用 base64 编码将 myFile 转换为字符串,但没有成功。
部分起作用的是将 myFile 转换为字符串,例如 str(myFile)。 json 序列化器工作,我通过套接字发送它,dict 没问题,但 myFile 数据已损坏,所以我无法重新创建图片。
那么是否可以使用这种方法,或者我应该如何通过套接字发送文件和数据以便在另一端轻松解析?
乐:
仍然无法使用 base64 编码,myFile 仍然是“字节”格式并且 json 给出这个错误:TypeError: Object of type 'bytes' is not JSON serializable
客户
import os
import base64
import json
import socket
currentPath = os.path.dirname(os.path.abspath(__file__)) + "\\downloads\\"
with open(currentPath + "cat.png", "rb") as f:
l = f.read()
print(type(l)) #prints <class 'bytes'>
myFile = base64.b64encode(l)
print(type(myFile)) #prints <class 'bytes'>
data = {"id": "12", "filename": "cat.png", "message": "So cute!", "file": myFile}
dataToSend = json.dumps(data).encode("utf-8") #prints TypeError: Object of type 'bytes' is not JSON serializable
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 1234))
s.sendall(dataToSend)
s.close()
还有服务器:
import socket
import json
import os
import sys
import time
import base64
currentPath = os.path.dirname(os.path.abspath(__file__)) + "\\fileCache\\"
tempData = bytearray()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 1234))
s.listen(5)
conn, addr = s.accept()
while True:
dataReceived = conn.recv(2048)
if sys.getsizeof(dataReceived) > 17:
tempData = tempData + dataReceived
else:
data = json.loads(tempData.decode("utf-8"))
break
time.sleep(1)
print(data)
myFile = base64.b64decode(data["file"])
with open(currentPath + data["filename"], "wb") as f:
f.write(myFile)
f.close()
【问题讨论】:
-
你应该可以做到:
dataToSend = json.dumps({"id":"1283", "filename":"cat.jpeg", "file":base64.b64encode(myFile)})就好了,这会给你带来什么错误? -
为什么不直接发送二进制数据而不是将其编码为base64并在此过程中浪费1/3的带宽?您可以像
<json_size><json><binary_size><binary_data>这样打包数据,其中大小可以是 4 字节,这将涵盖所有情况,直到 4GB 数据。 -
@zwer 我是编程新手,我不知道该怎么做。如果您知道要搜索的示例或某些关键字会很棒。
标签: python file sockets dictionary send