Issue
I need to transfer an Excel spreadsheet which includes charts and data from the backend (python) to the frontend (Angular-Javascript). To utilize the httpclient, I need to code the binary data in JSON as:
the_data = None
with open(output_file_path, mode='rb') as file:
output_file = file.read()
if output_file:
binary_data = base64.encodebytes(output_file).decode('utf-8')
the_data = {
'file': binary_data,
'name': 'export.xlsx',
'type': 'file'
}
dump_str = json.dumps(the_data)
js = json.loads(dump_str)
return js
Then on the front-end, I am trying to decode the data and save it to an excel file:
import * as FileSaver from 'file-saver';
...
this._service.export(request).subscribe((data:{}) => {
const name = (data as any)['name']
const b64Data = (data as any)['file'];
const byteCharacters = atob(b64Data);
const data: Blob = new Blob([byteCharacters], { type: application/octet- stream" });
FileSaver.saveAs(data, name);
});
The binary stream data look close but still different, and the saved export.xlsx cannot be opened by Excel. Any one knows what is the missing step?
Solution
Finally I figured out with hints from Creating a BLOB from a Base64 string in JavaScript The front-end should be:
import * as FileSaver from 'file-saver';
...
this._service.export(request).subscribe((data:{}) => {
const name = (data as any)['name']
const b64Data = (data as any)['file'];
const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const data: Blob = new Blob([byteArray], { type: "application/octet- stream" });
FileSaver.saveAs(data, name);
});
Answered By - xymzh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.