[英]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后端读取二进制文件,base64对其进行编码,将其插入JSON文档并将其发送到JavaScript前端:
#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前端从JSON文档中获取base64编码的字符串并将其转换为二进制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. 不幸的是,当下载blob时,编码似乎是错误的,但我不确定问题出在哪里。 Eg it is an Excel file that I can't open anymore. 例如,它是一个我无法打开的Excel文件。 In the Python part I've tried different decoders ('ascii', 'latin1') but that doesn't make a difference. 在Python部分我尝试了不同的解码器('ascii','latin1'),但这没有什么区别。 Is there a problem with my code? 我的代码有问题吗?
I found the answer here . 我在这里找到了答案。 The problem was at the JavaScript side. 问题出在JavaScript方面。 It seems only applying atob
to the base64 encoded string doesn't work for binary data. 似乎只将atob
应用于base64编码的字符串不适用于二进制数据。 You'll have to convert that into a typed byte array. 您必须将其转换为类型化的字节数组。 What I ended up doing (LiveScript): 我最终做了什么(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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.