PHP前端开发

html怎么读取本地文本文件

百变鹏仔 4周前 (09-21) #HTML
文章标签 文本文件
html自身无法直接读取本地文件,但可以通过以下方法解决:使用filereader api:使用filereader api的readastext()方法读取文本文件内容。使用xmlhttprequest:使用xmlhttprequest (xhr)向服务器发送http请求来读取本地文件。使用fetch api:使用fetch api发送http请求,类似于xmlhttprequest,但提供更现代的方式。

如何在 HTML 中读取本地文本文件

HTML 自身无法直接访问本地文件系统。但是,我们可以通过以下方法解决这个问题:

使用 FileReader API

FileReader API 提供了 readAsText() 方法,可用于读取文本文件内容:

立即学习“前端免费学习笔记(深入)”;

<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>

使用 XMLHttpRequest

XMLHttpRequest (XHR) 是一种通过 HTTP 请求与服务器交互的 API。我们可以使用它来读取本地文件:

<script>  const request = new XMLHttpRequest();  request.open('GET', 'local-file.txt');  request.onload = () => {    const text = request.responseText;    // 使用 text  };  request.send();</script>

使用 Fetch API

Fetch API 是 XHR 的替代方案,提供了一个更现代的方式来处理 HTTP 请求:

<script>  fetch('local-file.txt')  .then(response => response.text())  .then(text => {    // 使用 text  })  .catch(error => {    // 处理错误  });</script>

注意:由于安全原因,这些方法只能读取同一来源(域、协议和端口)的文本文件。