search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
1. Get a File via <input type="file">
2. Read Different File Types
3. Handle Multiple Files or Drag-and-Drop
4. Check File Info Before Reading
Home Web Front-end H5 Tutorial How to Read Local Files with the HTML5 File API? (JavaScript Example)

How to Read Local Files with the HTML5 File API? (JavaScript Example)

Dec 21, 2025 am 04:41 AM

浏览器中读取本地文件需用户交互触发,通过File API获取File对象并用FileReader加载内容;支持文本、DataURL、ArrayBuffer等读取方式,可验证文件类型与大小。

How to Read Local Files with the HTML5 File API? (JavaScript Example)

To read local files in the browser using the HTML5 File API, you need user interaction—like a file input or drag-and-drop—to obtain a File object, then use a FileReader to load its content. You cannot directly access files by path due to security restrictions.

1. Get a File via <input type="file">

Start with an HTML file input. When the user selects a file, the change event gives you access to the selected FileList.

Example:

&lt;input type="file" id="fileInput"&gt;
&lt;div id="output"&gt;&lt;/div&gt;

In JavaScript:

const fileInput = document.getElementById('fileInput');
const output = document.getElementById('output');
<p>fileInput.addEventListener('change', (e) =&gt; {
if (e.target.files.length === 0) return;</p><p>const file = e.target.files[0]; // First selected file
const reader = new FileReader();</p><p>reader.onload = () =&gt; {
output.textContent = reader.result; // Content appears here
};</p><p>reader.onerror = () =&gt; {
output.textContent = 'Error reading file.';
};</p><p>// Choose how to read: text, data URL, array buffer, etc.
reader.readAsText(file); // For plain text files
});</p>

2. Read Different File Types

FileReader supports several reading methods depending on your needs:

  • readAsText(file, encoding) — Best for UTF-8 text, JSON, CSV, or config files. Encoding defaults to "UTF-8".
  • readAsDataURL(file) — Returns a base64-encoded string (e.g., useful for previewing images).
  • readAsArrayBuffer(file) — Gives raw binary data; needed for parsing binary formats like PDFs or audio with TypedArray.
  • readAsBinaryString(file) — Deprecated; avoid unless supporting very old browsers.

3. Handle Multiple Files or Drag-and-Drop

You can also accept files via drag-and-drop. Listen for drop on a target element, prevent default behavior, and extract event.dataTransfer.files:

const dropArea = document.getElementById('dropArea');
dropArea.addEventListener('drop', (e) =&gt; {
  e.preventDefault();
  const files = e.dataTransfer.files;
  if (files.length === 0) return;
<p>const file = files[0];
const reader = new FileReader();
reader.onload = () =&gt; console.log('Loaded:', reader.result);
reader.readAsText(file);
});</p><p>dropArea.addEventListener('dragover', (e) =&gt; e.preventDefault());</p>

4. Check File Info Before Reading

Before loading, inspect properties like name, size, and type to validate or guide behavior:

  • file.name — Filename (e.g., "report.pdf")
  • file.size — Size in bytes (useful for limiting uploads)
  • file.type — MIME type (e.g., "text/plain", "image/png") — note: it's based on extension or OS hints, not file content

Example validation:

if (file.type !== 'text/csv') {
  alert('Please select a CSV file.');
  return;
}
if (file.size &gt; 5 * 1024 * 1024) { // 5MB limit
  alert('File too large.');
  return;
}

The above is the detailed content of How to Read Local Files with the HTML5 File API? (JavaScript Example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)