惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
O
OpenAI News
V
V2EX
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
小众软件
小众软件
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - Franky
Security Latest
Security Latest
S
SegmentFault 最新的问题
Project Zero
Project Zero
Spread Privacy
Spread Privacy
K
Kaspersky official blog
J
Java Code Geeks
V
Vulnerabilities – Threatpost
C
Cisco Blogs
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
T
The Exploit Database - CXSecurity.com
L
Lohrmann on Cybersecurity
人人都是产品经理
人人都是产品经理
博客园 - 三生石上(FineUI控件)
Scott Helme
Scott Helme
WordPress大学
WordPress大学
量子位
T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
AWS News Blog
AWS News Blog
Help Net Security
Help Net Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Simon Willison's Weblog
Simon Willison's Weblog
S
Secure Thoughts
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
V
Visual Studio Blog
Last Week in AI
Last Week in AI
T
Tailwind CSS Blog
腾讯CDC
Cyberwarzone
Cyberwarzone
IT之家
IT之家
GbyAI
GbyAI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
云风的 BLOG
云风的 BLOG
T
Troy Hunt's Blog
D
Docker

开飞机的老张

AGENTS.md Openspec 使用心得 从树莓派内网穿透到 Cloudflare Pages Openclaw和博客 郊眠寺 采石 译:我为什么使用Map(和WeakMap)处理DOM节点 介绍JavaScript中Symbol 原生JavaScript获取URL参数 字符串首字母大写 用forEach()遍历对象 JavaScript禁用按钮 JavaScript的FormData JavaScript的Blob JavaScript的Thenable JavaScript中Promise的reject JavaScript的立即调用函数表达式(IIFE) JavaScript的Promise链 用interact.js实现拖拽、缩放、吸附
用FileReader读取本地文件
kaifeiji.cc · 2023-07-25 · via 开飞机的老张

原文:Read Local Files in JavaScript with FileReader

FileReader类可以从原生的文件input中读取文件。

JavaScript的FileReader可以在浏览器中读取用户机器上的文件。FileReader一般通过<input type="file">来读取数据。

例如,在页面上有一个id为select-file的文件input,可以用以下代码打印选中文件的内容。

1
2
3
4
5
6
7
8
9
const file = document.querySelector('#select-file').files[0];
const reader = new FileReader();

reader.onload = res => {
console.log(res.target.result);
};
reader.onerror = err => console.log(err);

reader.readAsText(file);

以下是一个实例,可以在每次选择不同文件时,在控制台输出文件的内容。在Linux/Windows中按Ctrl+Shift+J,或在OSX中按Cmd+J,打开Chrome的控制台,然后试试吧!

静态博客无法显示,请查看原文

FileReader在现代浏览器和IE10中支持良好。需要注意FileReader是浏览器的API,所以大部分浏览器支持,但FileReader并不是Node.js的一部分。

Promise和async/await
FileReader类的异步API在配合async/awaitPromise链使用时并不是很理想。以下代码将FileReader包裹在Promise中,可以用于链式操作:

1
2
3
4
5
6
7
8
9
10
11
12
function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();

reader.onload = res => {
resolve(res.target.result);
};
reader.onerror = err => reject(err);

reader.readAsText(file);
});
}

有了以上的readFile()帮助函数,可以在异步函数中读取文件:

1
2
3
4
5
async function onSubmit() {
const file = document.querySelector('#select-file').files[0];

const contents = await readFile(file);
}

本教程对您有帮助吗?来GitHub仓库点个星支持我们吧!