I'm sending a file as follows.
with open(file,'rb') as f:
rh=f.read()
Now to send it I'm using
sock.sendto(rh, (ip,port))
While receiving I'm trying to decode this as follows.
dat = sock.recvfrom()
data=dat.decode('ascii')
Then I'm writing this to a file. This works perfectly fine in case of a text file. But If I'm sending and receiving a image/pdf file, I get this error ..
File "code.py", line 16, in <module>
data=dat.decode('ascii')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 41: ordinal not in range(128)
I'm not able to find out what's the problem here. I have also used dat.decode('utf-8') but no use
Try opening the file using codecs
.
import codecs
f = codecs.open(filepath, encoding="ISO8859-1")
Worked for me when I was uploading a PDF file using an API.
There's no need to decode. You read and sent the file in binary mode, so write the received file in binary mode. encode
/ decode
is meant for translating Unicode text to and from a binary representation.
with open(output_filename,'wb') as f:
f.write(data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.