Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 encode in python, decode in javascript

A Python backend reads a binary file, base64 encodes it, inserts it into a JSON doc and sends it to a JavaScript frontend:

#Python
with open('some_binary_file', 'rb') as in_file:
    return base64.b64encode(in_file.read()).decode('utf-8')

The JavaScript frontend fetches the base64 encoded string from the JSON document and turns it into a binary blob:

#JavaScript
b64_string = response['b64_string'];
decoded_file = atob(b64_string);
blob = new Blob([decoded_file], {type: 'application/octet-stream'});

Unfortunately when downloading the blob the encoding seems to be wrong but I'm not sure where the problem is. E.g. it is an Excel file that I can't open anymore. In the Python part I've tried different decoders ('ascii', 'latin1') but that doesn't make a difference. Is there a problem with my code?

like image 222
Berco Beute Avatar asked Feb 16 '16 21:02

Berco Beute


1 Answers

I found the answer here. The problem was at the JavaScript side. It seems only applying atob to the base64 encoded string doesn't work for binary data. You'll have to convert that into a typed byte array. What I ended up doing (LiveScript):

byte_chars = atob base64_str
byte_numbers = [byte_chars.charCodeAt(index) for bc, index in byte_chars]
byte_array = new Uint8Array byte_numbers
blob = new Blob [byte_array], {type: 'application/octet-stream'}
like image 78
Berco Beute Avatar answered Sep 21 '22 15:09

Berco Beute