Home  >  Article  >  Web Front-end  >  How to open local file in html

How to open local file in html

下次还敢
下次还敢Original
2024-04-22 09:39:171192browse
<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>How to open local file in html

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

  1. <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).
  2. <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:
    <code class="html"><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></code>
  3. <p>Create the input field:

    • Add an <input> element to allow the user to select a file to open:
    <code class="html"><input type="file"></code>
  4. <p>Listen to the file selection event:

    • Use jQuery's change() event to listen to the file selection:
    <code class="html"><script>
    $("input[type=file]").change(function() {
      // 文件选择后执行此函数
    });
    </script></code>
  5. <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:
    <code class="javascript">var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function() {
      // 读取的文件内容存储在 `reader.result` 中
    };
    reader.readAsText(file);</code>
  6. <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:

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn