简体   繁体   English

是否可以将字节数组/流转换为JavaScript中的Word,Excel,PDF等文件

[英]Is it possible to convert byte array/stream to files such as Word,Excel, PDF in JavaScript

I have a query regarding file operations using JavaScript- 我有一个有关使用JavaScript进行文件操作的查询-

Scenario - My JS function calls a wcf service which returns the file content in the form of byte array or stream and the mime type. 场景-我的JS函数调用wcf服务,该服务以字节数组或流以及mime类型的形式返回文件内容。 This byte array/stream needs to be converted to a file and which will be downloaded on user's machine. 该字节数组/流需要转换为文件,并将其下载到用户的计算机上。
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);

The code works for only text files. 该代码仅适用于文本文件。 Files with mime type other than text are corrupted. MIME类型不是文本的文件已损坏。 I understand that file operations are severly restricted at client side, but just to confirm - Is there anyway to convert byte array/stream to files such as Word,Excel, PDF and etc ? 我知道文件操作在客户端受到了严格限制,但只是为了确认-是否总有将字节数组/流转换为Word,Excel,PDF等文件的方法?

I accomplish a similar goal with this. 为此,我实现了类似的目标。 Pick up from where you have your byteArray, and try this: 从您拥有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)

Setting contentType to "application/octet-stream" will accommodate any binary file type. 将contentType设置为“ application / octet-stream”将适应任何二进制文件类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM