Python Forum

Full Version: Python3: how to read binary?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!

I try to upload mp4 video file. When I use Python 2+ it works. When I use Python 3 - not

I read the file as binary.

def get_file_data(path):
    with open(path, 'rb') as f:
        fdata = f.read()       
    return fdata

dct = {}
dct['title'] = 'My title'
dct['video_data'] = get_file_data('test.mp4')

print(video_data[:50])
b'\x00\x00\x00 ftypisom\x00\x00\x02\x00isomiso2avc1mp41\x00\x00\x00\x08free%\x9d\xbb\xd7mdat\xff\xfb'
After that I make data, add header and try to post(upload).

data = '''-----------------------------48532483525862
Content-Disposition: form-data; name="title"

{title}
-----------------------------48532483525862
Content-Disposition: form-data; name="Filedata"; filename="test.mp4"
Content-Type: video/mp4

{video_data}
-----------------------------48532483525862--'''.format(**dct)


s.headers['Content-Type'] = 'multipart/form-data; boundary=-----------------------------48532483525862'

resp = s.post(upload_url, data)
But remote server returns error

"message":"Expecting a file during post.","code":0

I think it's because of bytes. I tried to decode fdata.decode('latin-1'), but this is useless. Server returns error.