HTML itself cannot directly read local files, but it can be solved by the following methods: Using the FileReader API: Use the readAsText() method of the FileReader API to read the text file content. Using XMLHttpRequest: Use XMLHttpRequest (XHR) to send an HTTP request to the server to read a local file. Using Fetch API: Use Fetch API to send HTTP requests, similar to XMLHttpRequest, but providing a more modern way.
How to read local text files in HTML
HTML itself cannot directly access the local file system. However, we can solve this problem by the following methods:
Use the FileReader API
The FileReader API provides the readAsText()
method, which can be used to read Get text file content:
<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></code>
Using XMLHttpRequest
XMLHttpRequest (XHR) is an API that interacts with the server through HTTP requests. We can use this to read local files:
<code class="html"><script> const request = new XMLHttpRequest(); request.open('GET', 'local-file.txt'); request.onload = () => { const text = request.responseText; // 使用 text }; request.send(); </script></code>
Using Fetch API
Fetch API is an alternative to XHR and provides a more modern way to handle HTTP Request:
<code class="html"><script> fetch('local-file.txt') .then(response => response.text()) .then(text => { // 使用 text }) .catch(error => { // 处理错误 }); </script></code>
NOTE: Due to security reasons, these methods can only read text files from the same source (domain, protocol and port).
The above is the detailed content of How to read local text files in html. For more information, please follow other related articles on the PHP Chinese website!