我有一个关于使用 JavaScript 进行文件操作的查询 -
场景 - 我的 JS 函数调用 wcf 服务,该服务以字节数组或流和 mime 类型的形式返回文件内容。该字节数组/流需要转换为文件并将其下载到用户的计算机上。
<强> Reference code -
var arr = "This is test content";
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], {
type: 'text/plain'
}));
a.download = "Test";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
该代码仅适用于文本文件。 MIME 类型非文本的文件已损坏。 我知道文件操作在客户端受到严格限制,但只是为了确认 - 是否有办法将字节数组/流转换为 Word、Excel、PDF 等文件?
最佳答案
我用这个实现了类似的目标。从您拥有 byteArray 的位置开始,然后尝试以下操作:
var byteArray = new Uint8Array(arrayBuffer);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));
// supply your own fileName here...
a.download = "YourFileName.XLSX";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
将 contentType 设置为“application/octet-stream”将适应任何二进制文件类型。
关于javascript - 是否可以在JavaScript中将字节数组/流转换为Word、Excel、PDF等文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33124044/