<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:
-
<p>Create HTML file:
- Use a text editor ( such as Notepad or Sublime Text) to create a new file.
- Save the file with the
.html
extension (for example: myfile.html
).
-
<p>Import jQuery:
- jQuery is a JavaScript library that makes manipulating HTML elements easier.
- Add the following code to the
<head>
section of the HTML file:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Copy after login
- <p>Create the input field:
- Add an
<input>
element to allow the user to select a file to open:
<input type="file">
Copy after login
- <p>Listen to the file selection event:
- Use jQuery's
change()
event to listen to the file selection:
<script>
$("input[type=file]").change(function() {
// 文件选择后执行此函数
});
</script>
Copy after login
- <p>Handling file selection:
- In the event handler function, get the selected file and use the
FileReader()
object to read the contents of the file:
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
// 读取的文件内容存储在 `reader.result` 中
};
reader.readAsText(file);
Copy after login
- <p>Display file content:
- After reading the file content, you can use HTML elements (such as
<div>
or <p>
) to display it on the web page.
<p>
Sample code:
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<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>