Home >Web Front-end >HTML Tutorial >How to read local files in html

How to read local files in html

下次还敢
下次还敢Original
2024-04-11 09:18:001199browse

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 read local files in html

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:

  1. Create a file selector using the <input> element:

    <input type="file">

  2. ##Add an event listener to the file selector:

    <code class="javascript">const input = document.querySelector('input[type="file"]');
    input.addEventListener('change', handleFileSelect);</code>
  3. 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:

    File API only works with HTML5 browsers.
  • Reading local files requires explicit authorization from the user.
  • Browsers have specific restrictions on file size and type.
  • Use the File API with caution as it may cause security risks.

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!

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