Reputation: 305
I want save an excel file as json in database. It is then downloaded in the python backend later on to create the excel file.
My frontend to save excel file as json:
const fileReader: FileReader = new FileReader();
fileReader.onloadend = (_x) => {
const input: any = {
name: file.name,
content: {
author: 'username',
excelFile: fileReader.result,
},
};
httprequest({params: input}).subscribe();
};
fileReader.readAsDataURL(file);
Python backend to create excel file from json:
data = api_client.get_file_details(id)
decoded_excel = base64.b64decode(data["content"]["excelFile"])
with open('example.xlsx', "wb") as f:
f.write(decoded_excel)
Unfortunately python decoding does not work. It gives error Error: Invalid base64-encoded string: number of data characters (587469) cannot be 1 more than a multiple of 4
. How can solve this issue?
Upvotes: 0
Views: 48
Reputation: 643
The format of the result
attribute is data:[<mediatype>];base64,<data>
, which cannot be directly decoded as Base64 since it includes the Data-URL declaration. You should remove that part first. Like:
data = api_client.get_file_details(id)
decoded_excel = base64.b64decode(data["content"]["excelFile"].split(',', 1)[1])
with open('example.xlsx', "wb") as f:
f.write(decoded_excel)
Upvotes: 0