Home >Web Front-end >HTML Tutorial >How to open local file in html
<p>HTML can be used to open local files as follows: Create a .html file and import the jQuery library. Create an input field that allows the user to select a file. Listen to the file selection event and use a FileReader() object to read the file contents. Display the read file contents on the web page.<p> <p>How to open a local file using HTML <p>HTML (Hypertext Markup Language) is commonly used to create web pages, but It can also be used to read and display local files. <p> Steps:
.html
extension (for example: myfile.html
). <head>
section of the HTML file: <code class="html"><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></code>
<input>
element to allow the user to select a file to open: <code class="html"><input type="file"></code>
change()
event to listen to the file selection: <code class="html"><script> $("input[type=file]").change(function() { // 文件选择后执行此函数 }); </script></code>
FileReader()
object to read the contents of the file: <code class="javascript">var file = this.files[0]; var reader = new FileReader(); reader.onload = function() { // 读取的文件内容存储在 `reader.result` 中 }; reader.readAsText(file);</code>
<div>
or <p>
) to display it on the web page. <code class="html"><!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <input type="file"> <script> $("input[type=file]").change(function() { var file = this.files[0]; var reader = new FileReader(); reader.onload = function() { $("#result").html(reader.result); }; reader.readAsText(file); }); </script> <div id="result"></div> </body> </html></code>
The above is the detailed content of How to open local file in html. For more information, please follow other related articles on the PHP Chinese website!