想要简单地将用户输入的文件读取为文本。
可以依赖于现代浏览器的使用,所以我为此使用了 FileReader(效果很好)。
reader.readAsText(myfile, encoding);
我知道编码
默认为UTF-8。
但由于我的用户将从各种来源(Windows、Mac、Linux)和各种浏览器上传文件,我要求用户通过选择框提供编码。
例如对于西欧 Windows 文本文件,我希望用户选择例如windows-1252.
我找不到 FileReader 支持的编码列表(假设这至少取决于浏览器)。
我不是要求自动确定编码,我只是想以如下方式填写我的选择框:
<select id="encoding">
<option value="windows-1252">Windows (Western Latin)</option>
<option value="utf-8">UTF-8</option>
<option value="...">...</option>
</select>
所以我的问题是:
- 我在哪里可以获得支持的编码列表以填充选项值?
- 如何确定这些值的确切书写方式(是“utf8”还是“UTF-8”还是...)以及这些值是否取决于操作系统/浏览器?
- 如果不支持编码,readAsText(myfile, unsupportedEncoding) 会抛出任何我可以捕捉到的错误吗?
我不想为此使用任何主要的第 3 方库。
奖励问题:
是否有一种简单的方法来获取值的有意义翻译,例如cp10029 表示 Mac(中欧)?
最佳答案
- 编码标准 - https://github.com/whatwg/encoding/ (采用 JSON 格式 - https://github.com/whatwg/encoding/blob/master/encodings.json。使用“标签”字段中的值)
编码参数不区分大小写。
不,readAsText(myfile, unsupportedEncoding) 不会抛出任何错误。该函数仅使用默认编码(“utf8”)。
window.onload = function() { //Check File API support if (window.File && window.FileList && window.FileReader) { var filesInput = document.getElementById("files"); filesInput.addEventListener("change", function(event) { var files = event.target.files; //FileList object var output = document.getElementById("result"); for (var i = 0; i < files.length; i++) { var file = files[i]; //Only plain text if (!file.type.match('plain')) continue; var picReader = new FileReader(); picReader.addEventListener("load", function(event) { var textFile = event.target; var div = document.createElement("div"); div.innerText = textFile.result; output.insertBefore(div, null); }); //Read the text file picReader.readAsText(file, "cP1251"); } }); } else { console.log("Your browser does not support File API"); } }
要获取值的翻译,您可以使用 JSON 文件 ( https://github.com/whatwg/encoding/blob/master/encodings.json )、参数“heading”和“name”。
关于javascript - FileReader - 支持哪些编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790042/