Platform
Resources
Pricing
Sign in
Get started
specialCoder
前端 摄影 文学
Workspace
Fork
Published
javascript 二进制
By
specialCoder
Edited
Jun 9, 2020
javascript 二进制
File&FileReader
Blob介绍
ArrayBuffer(二进制数组)
TextDecoder 和 TextEncoder
Insert cell
md
`# File&FileReader`
Insert cell
md
` ## File`
Insert cell
md
`
File 对象继承自 Blob。
除了 Blob 方法和属性外,File 对象还有 name 和 lastModified 属性,以及从文件系统读取的内部功能。我们通常从用户输入如 input标签 或拖放事件来获取 File 对象。
\`\`\`
new File(fileParts, fileName, [options])
\`\`\`
- fileParts —— Blob/BufferSource/String 类型值的数组。
- fileName —— 文件名字符串。
- options —— 可选对象:
- lastModified —— 最后一次修改的时间戳(整数日期)。
`
Insert cell
html
`<input type="file" onchange="showFile(this)">`
Insert cell
function
showFile
(
input
)
{
let
file
=
input
.
files
[
0
]
;
alert
(
`File name: ${
file
.
name
}`
)
;
// 例如 my.png
alert
(
`Last modified: ${
file
.
lastModified
}`
)
;
// 例如 1552830408824
}
Insert cell
md
`## FileRender`
Insert cell
md
`
** 唯一目的是从 Blob(因此也从 File)对象中读取数据。**
\`\`\`
let reader = new FileReader(); // 没有参数
\`\`\`
主要方法:
- readAsArrayBuffer(blob) —— 将数据读取为二进制格式的 ArrayBuffer。
- readAsText(blob, [encoding]) —— 将数据读取为给定编码(默认为 utf-8 编码)的文本字符串。
- readAsDataURL(blob) —— 读取二进制数据,并将其编码为 base64 的 data url。
- abort() —— 取消操作。
`
Insert cell
md
`
读取过程中,有以下事件:
- loadstart —— 开始加载。
- progress —— 在读取过程中出现。
- load —— 读取完成,没有 error。
- abort —— 调用了 abort()。
- error —— 出现 error。
- loadend —— 读取完成,无论成功还是失败。
读取完成后,我们可以通过以下方式访问读取结果:
- reader.result 是结果(如果成功)
- reader.error 是 error(如果失败)。
`
Insert cell
html
`<input type="file" onchange="readFile(this)">`
Insert cell
function
readFile
(
input
)
{
let
file
=
input
.
files
[
0
]
;
let
reader
=
new
FileReader
(
)
;
reader
.
readAsText
(
file
)
;
reader
.
onload
=
function
(
)
{
console
.
log
(
reader
.
result
)
;
}
;
reader
.
onerror
=
function
(
)
{
console
.
log
(
reader
.
error
)
;
}
;
}
Insert cell
Purpose-built for displays of data
Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Try it for free
Learn more
Fork
View
Export
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
showFile
Add comment
Copy import
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
Add comment
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML
readFile
Add comment
Copy import
Select
Duplicate
Copy link
Embed
Delete
JavaScript
Markdown
HTML