Angular 13 - 从 ByteArray 数据下载文件

Iñi*_*igo 4 javascript file download typescript angular

byte[]从服务器获取一个包含文件内容的文件。我知道名字和content-type。到目前为止,我已尝试以下方法来下载文件:

const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';

const file = new Blob([content], {type: 'text/plain'});
const url = window.URL.createObjectURL(file);
a.href = url;
a.download = "test.txt";
a.click();
window.URL.revokeObjectURL(url);
Run Code Online (Sandbox Code Playgroud)

但这个解决方案只是下载一个包含二进制内容的文本文件。如何使用 JavaScript/Typescript 将二进制数据转换为客户端相应的文件类型?谢谢!

Adr*_*rma 10

您可以使用文件保护程序

import { saveAs } from 'file-saver';

const file = new Blob([content], {type: 'text/plain'});
FileSaver.saveAs(file, "test.txt");
Run Code Online (Sandbox Code Playgroud)