Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - How can I convert BinaryString to Array for TextDecoder?

I am using a third-party package named jschardet(https://github.com/aadsm/jschardet) to detect the encoding of the file.

Here is my code:

function FileUpload(input) {
     var reader = new FileReader();
            reader.onload = function (e) {
                Running = true;
                var Decoder = new TextDecoder(jschardet.detect(e.target.result).encoding);
                var text = Decoder.decode(e.target.result);
                alert(text);
                }
            }
            reader.readAsBinaryString(input);   
}

The jschardet gets the encoding very well and I need to decode the text with the right encoding. However, the TextDecoder can not convert the BinaryString directly. It throws an error:

Test.min.js:1 Uncaught TypeError: Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'
    at FileReader.r.onload (Test.min.js:1)

How can I solve this? Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since jschardet doesn't seem to handle ArrayBuffer, you pass it a binary string and convert it to Buffer for decoding.

function FileUpload(input) {
  var reader = new FileReader();
  reader.onload = function () {
    const { encoding } = jschardet.detect(reader.result);
    var Decoder = new TextDecoder(encoding);
    var text = Decoder.decode(new Buffer(reader.result, "binary"));
    alert(text);
  };
  reader.readAsBinaryString(input);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...