Home >Web Front-end >HTML Tutorial >How to read local files in html
In HTML, read local files through File API. The steps include: Create a file selector using the <input> element. Add an event listener to the file picker. In the event handler, use a FileReader object to read the file. After a successful read, the result attribute contains the file contents and can be processed as needed.
How to use HTML to read local files
In HTML, reading local files is mainly done by using the File API . The File API is a set of JavaScript APIs that allow web pages to read files from user devices.
Steps required:
Create a file selector using the <input>
element:
<input type="file">
##Add an event listener to the file selector:
<code class="javascript">const input = document.querySelector('input[type="file"]'); input.addEventListener('change', handleFileSelect);</code>
Read file in event handler:
<code class="javascript">function handleFileSelect(event) { const files = event.target.files; const reader = new FileReader(); reader.onload = function() { // 读取成功后,`result` 属性将包含文件的内容。 const content = reader.result; // 对文件内容执行所需的处理。 }; reader.readAsText(files[0]); }</code>
Sample code:
<code class="html"><form> <input type="file" id="file-input"> <button type="submit">读取文件</button> </form> <script> const input = document.querySelector('input[type="file"]'); input.addEventListener('change', function(event) { const files = event.target.files; const reader = new FileReader(); reader.onload = function() { const content = reader.result; console.log(content); }; reader.readAsText(files[0]); }); </script></code>
Note:
The above is the detailed content of How to read local files in html. For more information, please follow other related articles on the PHP Chinese website!