Трипольский Пётр Asked:2020-03-10 00:52:48 +0000 UTC2020-03-10 00:52:48 +0000 UTC 2020-03-10 00:52:48 +0000 UTC 如何从 JavaScript 读取上传到表单的文本文件? 772 我需要编写一个处理 CSV 文档的 Web 应用程序,每个文档大约有 2000 万行。它本身仍然什么都不是,但标准的 FileReader 对象只有一个读取整个文件的方法,我需要显示进程栏。另外,我担心程序可能会因为这么长的一行而挂起。 javascript 1 个回答 Voted Best Answer Трипольский Пётр 2020-03-10T00:52:48Z2020-03-10T00:52:48Z 您可以将Uint8Array与new FileReader().readAsArrayBuffer()一起使用。只需通过 "\n".charCodeAt(0) 将数组拆分为多个部分,然后使用TextDecoder进行解码。 <html> <head> <script> const r_char_code = "\r".charCodeAt(0); function detectEncoding(subArr,func){ const isUnicode = subArr[subArr.length-1]!=r_char_code; const decoder = isUnicode?new TextDecoder():new TextDecoder('windows-1251'); const str = decoder.decode(subArr); console.log({ result: str, encoding: isUnicode?"utf-8":"windows-1251" }); func(str); } function parseByteArray(arr,func){ let tmp = []; arr.forEach((byte,i)=> { const char = String.fromCharCode(byte); if(char!='\n'){ tmp.push(byte); } //line by line or EOF if(char=='\n'||i==arr.length-1){ const buf = Uint8Array.from(tmp); for(let i=0;i!=tmp.length+1;i++){ buf[i]=tmp[i]; } detectEncoding(buf,func); tmp=[]; } }); } function readFileAsByteArray(file){ const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onloadend=()=>{ if(reader.error){ throw new Errow(":-("); } parseByteArray(new Uint8Array(reader.result), console.log); } } function readLineByLine(){ const input = document.createElement('input'); input.type = 'file'; input.accept = '.txt,.csv,.md'; input.click(); input.onchange = ()=>{ readFileAsByteArray(input.files[0]); } } </script> </head> <body> <button onclick="readLineByLine()">Go!</button> </body> 您可以在pasteBin上查看
您可以将Uint8Array与new FileReader().readAsArrayBuffer()一起使用。只需通过 "\n".charCodeAt(0) 将数组拆分为多个部分,然后使用TextDecoder进行解码。
您可以在pasteBin上查看