Long story short, I'm sending an Excel file from Python to Javascript. To do so, I need to send it as a string (very dirty but this is a constraint on my side), and so, I "hexlify" (or use .hex(), any way to do it is ok as long as it works in the Javascript) my Excel file in Python and send it to the Javascript.
with open(EXCEL_TEMPLATE_OUTPUTS, "rb") as f:
encrypted_bytes = f.read()
return encrypted_bytes.hex()
The difficulty now is to convert it back to an array of bytes in the Javascript, so that I can create a Blob. To do so, I'm using the function below:
var unhexlify = function(str) {
var bytes = [];
for (var i=0, l=str.length; i<l; i+=2) {
bytes.push(String.fromCharCode(parseInt(str.substr(i, 2), 16)));
}
return bytes;
It works quite well except for some characters. For example, "c8" is converted into "È" instead of "\xc8". So, the file I'm rebuilding is corrupted. Is there any way to overcome this issue?
EDIT: Here below is an example highlighting the problem:
console.log(String.fromCharCode(parseInt("c8", 16)));
As you can see, it is sending "È" instead of "\xc8", while in Python:
from binascii import hexlify, unhexlify
unhexlify("c8")
# b'\xc8'
bytes.fromhex('c8')
# b'\xc8'
I've finally found a solution that actually get rid of String.fromCharCode(). The idea here is to create a Uint8Array from the hex sent from Python:
var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {return parseInt(h, 16)}))
I can then create a blob based on this Uint8Array:
const blob = new Blob([typedArray], { type: "application/octet-stream" });
Thanks @Konrad. You guided me on the right path to find the solution!