2 分钟 读完 (大约 266 个字)
js实现txt文件预览(支持各种编码格式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
import jschardet from 'jschardet'
function checkEncoding (file) { return new Promise((resolve, reject) => { let reader = new FileReader() reader.readAsDataURL(file) reader.onload = function (e) { let base64Str = reader.result let str = atob(base64Str.split(';base64,')[1]) let encoding = jschardet.detect(str) encoding = encoding.encoding if (encoding === 'window-1252') { encoding = 'ANSI' } resolve(encoding) } }) }
const txtPreview = (file) => { return new Promise((resolve, reject) => { checkEncoding(file).then(encoding => { let reader = new FileReader() reader.readAsText(file, encoding) reader.onloadend = function (e) { resolve(reader.result) } }) }) } export default txtPreview
|
HTML代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <html> <body> <form> <input type="file" id="files" name="files"/> </form> <div id="resText" style="word-wrap: break-word; white-space: divpre-wrap;"></div> <script> import txtPreview from './txtPreview.js' document.getElementById('files').addEventListener('change', handleFileSelect, false); function handleFileSelect(e) { let file = e.target.files[0] txtPreview(file).then(res => { document.getElementById("resText").innerHTML = res; }) } </script> </body> </html>
|
本文参考文章: