如何在 HTML 中读取本地文本文件
HTML 自身无法直接访问本地文件系统。但是,我们可以通过以下方法解决这个问题:
使用 FileReader API
FileReader API 提供了 readAsText()
方法,可用于读取文本文件内容:
<code class="html"><input type="file" id="file-input"><script> const fileInput = document.getElementById(\'file-input\'); fileInput.addEventListener(\'change\', (e) => { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = (e) => { const text = e.target.result; // 使用 text }; reader.readAsText(file); }); </script>