E11 上的 JavaScript readAsBinaryString 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31391207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:38:30  来源:igfitidea点击:

JavaScript readAsBinaryString Function on E11

javascripthtmlinternet-explorer

提问by Dev.K.

In this page http://www.html5rocks.com/en/tutorials/file/dndfiles/if you scroll down to example "Example: Slicing a file. Try it!" you will see uses of readAsBinaryStringAPI to read bytes of local files.

在此页面 http://www.html5rocks.com/en/tutorials/file/dndfiles/如果您向下滚动到示例“示例:切片文件。试试看!” 您将看到使用readAsBinaryStringAPI 来读取本地文件的字节。

I've seen IE (My case its IE11) doesn't support readAsBinaryString.

我见过 IE(我的情况是 IE11)不支持readAsBinaryString

Even this code mentioned in post HTML5 File API read as text and binarybreaks at readAsBinaryStringin IE11.

甚至在HTML5 文件 API 中提到的这段代码在 IE11中的readAsBinaryString中也被读取为文本和二进制中断。

I have seen some post in stack overflow, it suggests use of ReadAsArrayBuffer(). But it is also not working. It returns undefined.

我在堆栈溢出中看到了一些帖子,它建议使用 ReadAsArrayBuffer()。但它也不起作用。它返回未定义。

My question is what are the options if I have to run it on IE11? Is it possible to write another IE compatible JS function which will do the JOB of readAsBinaryString().

我的问题是,如果我必须在 IE11 上运行它,有哪些选择?是否可以编写另一个 IE 兼容的 JS 函数来完成 readAsBinaryString() 的工作。

回答by Naigel

I combine @Hyman answer with my comment to show a complete working example.

我将@Hyman 的回答与我的评论结合起来,展示了一个完整的工作示例。

In the <head>section I added this script to add FileReader.readAsBinaryStringfunction in IE11

<head>我添加此脚本以FileReader.readAsBinaryString在 IE11 中添加功能的部分中

if (FileReader.prototype.readAsBinaryString === undefined) {
    FileReader.prototype.readAsBinaryString = function (fileData) {
        var binary = "";
        var pt = this;
        var reader = new FileReader();
        reader.onload = function (e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            //pt.result  - readonly so assign content to another property
            pt.content = binary;
            pt.onload(); // thanks to @Denis comment
        }
        reader.readAsArrayBuffer(fileData);
    }
}

Then I needed to slightly modify my original script code because target.resulthas no value when using this fallback function.

然后我需要稍微修改我的原始脚本代码,因为target.result在使用此回退函数时没有任何价值。

var reader = new FileReader();
reader.onload = function (e) {
    // ADDED CODE
    if (!e) {
        var data = reader.content;
    }
    else {
        var data = e.target.result;
    }

    // business code
};
reader.readAsBinaryString(myFile);

回答by Hyman

This is my solution.

这是我的解决方案。

var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
  if (reader.result) reader.content = reader.result;
  var base64Data = btoa(reader.content);
  //...
}
//extend FileReader
if (!FileReader.prototype.readAsBinaryString) {
    FileReader.prototype.readAsBinaryString = function (fileData) {
       var binary = "";
       var pt = this;
       var reader = new FileReader();      
       reader.onload = function (e) {
           var bytes = new Uint8Array(reader.result);
           var length = bytes.byteLength;
           for (var i = 0; i < length; i++) {
               binary += String.fromCharCode(bytes[i]);
           }
        //pt.result  - readonly so assign binary
        pt.content = binary;
        $(pt).trigger('onload');
    }
    reader.readAsArrayBuffer(fileData);
    }
}

回答by ozdefir

For IE 11 you can use this XHR trick:

对于 IE 11,您可以使用此 XHR 技巧:

function blobToBinaryStringIE11(blob) {
    var blobURL = URL.createObjectURL(blob);
    var xhr = new XMLHttpRequest;
    xhr.open("get", blobURL);
    xhr.overrideMimeType("text/plain; charset=x-user-defined");
    xhr.onload = function () {
        var binary = xhr.response;
        // do stuff
    };
    xhr.send();
}

It's 20x faster than the Uint8Array + fromCharCoderoute and as fast as readAsBinaryString.

它比Uint8Array + fromCharCode路线快20 倍,并且与readAsBinaryString.

回答by Jayendra Sharan

FileReader.readAsBinaryStringis a non-standard function and has been deprecated.

FileReader.readAsBinaryString是一个非标准函数,已被弃用。

FileReader.readAsArrayBuffershould be used instead.

FileReader.readAsArrayBuffer应该改用。

MDN

MDN

回答by user3292624

Replace

代替

reader.readAsBinaryString(blob);

with:

和:

reader.readAsText(blob);

it's works well in cross browser.

它在跨浏览器中运行良好。

回答by H Dog

I had some problems with the answers here and ended up making a few slight changes.

我在这里的答案有一些问题,最终做了一些细微的改变。

Instead of assigning to pt.content, my solution is to send a custom object to the prototype's onload, that receiver can specifically look for, I named this property msieContent so it will be very specific.

我的解决方案不是分配给 pt.content,而是将自定义对象发送到原型的 onload,该接收器可以专门查找,我将此属性命名为 msieContent,因此它将非常具体。

Also I used other accepted answer for converting Uint8Array to string in more robust way, you can see full details of it here: https://stackoverflow.com/a/12713326/213050

我还使用了其他公认的答案以更健壮的方式将 Uint8Array 转换为字符串,您可以在此处查看它的完整详细信息:https://stackoverflow.com/a/12713326/213050

Polyfill

填充物

if (FileReader.prototype.readAsBinaryString === undefined) {
    // https://stackoverflow.com/a/12713326/213050
    function Uint8ToString(u8a: Uint8Array) {
        const CHUNK_SZ = 0x8000;
        let c = [];
        for (let i = 0; i < u8a.length; i += CHUNK_SZ) {
            c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ)));
        }
        return c.join('');
    }
    FileReader.prototype.readAsBinaryString = function (fileData) {
        const reader = new FileReader();
        reader.onload = () => this.onload({
            msieContent: Uint8ToString(new Uint8Array(<any>reader.result))
        });
        reader.readAsArrayBuffer(fileData);
    }
}

Usage

用法

private _handleTextFile(file: File) {
    const reader = new FileReader();

    reader.onload = (e) => {
        // support for msie, see polyfills.ts
        const readResult: string = (<any>e).msieContent || <string>e.target.result;

    };

    reader.readAsBinaryString(file);
}