JavaScript readAsBinaryString Function on E11

后端 未结 6 1892
攒了一身酷
攒了一身酷 2020-12-23 18:35

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 readAsBin

6条回答
  •  没有蜡笔的小新
    2020-12-23 18:53

    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.

    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

    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(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 = (e).msieContent || e.target.result;
    
        };
    
        reader.readAsBinaryString(file);
    }
    

提交回复
热议问题