json 在Angular中,如何通过httpclient将数据从二进制文件传输到前端?

hk8txs48  于 2023-10-21  发布在  Angular
关注(0)|答案(1)|浏览(133)

我需要将一个Excel电子表格,其中包括从后端(Python)到前端(Angular-Javascript)的图表和数据。为了使用httpclient,我需要将JSON中的二进制数据编码为:

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

然后在前端,我试图解码数据并将其保存到Excel文件中:

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);
});

二进制流数据看起来很接近,但仍然不同,保存的export.xlsx无法通过Excel打开。有谁知道缺了什么?

2wnc66cl

2wnc66cl1#

最后,我从Creating a BLOB from a Base64 string in JavaScript的提示中弄清楚了前端应该是:

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);
});

相关问题