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

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:
<input type="file" id="fileInput"> <div id="output"></div>
In JavaScript:
const fileInput = document.getElementById('fileInput');
const output = document.getElementById('output');
<p>fileInput.addEventListener('change', (e) => {
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 = () => {
output.textContent = reader.result; // Content appears here
};</p><p>reader.onerror = () => {
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 withTypedArray. -
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) => {
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length === 0) return;
<p>const file = files[0];
const reader = new FileReader();
reader.onload = () => console.log('Loaded:', reader.result);
reader.readAsText(file);
});</p><p>dropArea.addEventListener('dragover', (e) => 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 > 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!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20529
7
13638
4




