Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert 'bytes' object to str implicitly

I am trying to open a gif file, and send its bytes properly to a webbrowser but it throws the exception 'cannot convert 'bytes' object to str implicitly' and frankly I am baffled, because I already converted it to a string.

files=open("WebContent/"+fileName,"rb")
#size=os.path.getsize("WebContent/"+fileName)
text=str(files.read())
text=text.encode('UTF-8')
defaultResponseCode="HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\nContent-Transfer-Encoding: binary\r\nContent-Length: 29696\r\n\r\n"+text

Thanks in advance!

like image 309
user1564622 Avatar asked Nov 10 '22 15:11

user1564622


1 Answers

Here you are trying to convert bytes (file opened with 'rb' mode) to string:

text = str(files.read())

change above line to this:

text = files.read().decode(encoding='change_to_source_file_encoding')

then you can convert unicode string to utf-8 byte string with:

text = text.encode('UTF-8')

And if source encoding is utf-8 you can just pass byte string from files.read() to your result string without senseless decode/encode steps (from utf-8 bytes to string and again to utf-8 bytes)...

update: try with requests

url = 'url'
files = {'file': open("WebContent/"+fileName, 'rb')}
response = requests.post(url, files=files)

update 2:

According to content-type in response header (... Content-Type: image/gif ...) you have data with needed format just after files.read() whithout any encoding/decoding!

like image 98
ndpu Avatar answered Nov 15 '22 06:11

ndpu