早就听说过断点续传这种东西,前端也可以实现一下
断点续传在前端的实现主要依赖着HTML5的新特性,所以一般来说在老旧浏览器上支持度是不高的
本文通过断点续传的简单例子(前端文件提交+后端PHP文件接收),理解其大致的实现过程
还是先以图片为例,看看最后的样子
一、一些知识准备
断点续传,既然有断,那就应该有文件分割的过程,一段一段的传。
以前文件无法分割,但随着HTML5新特性的引入,类似普通字符串、数组的分割,我们可以可以使用slice方法来分割文件。
所以断点续传的最基本实现也就是:前端通过FileList对象获取到相应的文件,按照指定的分割方式将大文件分段,然后一段一段地传给后端,后端再按顺序一段段将文件进行拼接。
而我们需要对FileList对象进行修改再提交,在相关资料中知晓了这种提交的一些注意点,因为FileList对象不能直接更改,所以不能直接通过表单的.submit()方法上传提交,需要结合FormData对象生成一个新的数据,通过Ajax进行上传操作。
二、实现过程
这个例子实现了文件断点续传的基本功能,不过手动的“暂停上传”操作还未实现成功,可以在上传过程中刷新页面来模拟上传的中断,体验“断点续传”、
有可能还有其他一些小bug,但基本逻辑大致如此。
1. 前端实现
首先选择文件,列出选中的文件列表信息,然后可以自定义的做上传操作
(1)所以先设置好页面DOM结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<!-- 上传的表单 -->
<form
method
=
"post"
id
=
"myForm"
action
=
"/fileTest.php"
enctype
=
"multipart/form-data"
>
<input
type
=
"file"
id
=
"myFile"
multiple
=
""
>
<!-- 上传的文件列表 -->
<table
id
=
"upload-list"
>
<thead>
<tr>
<th
width
=
"35%"
>
文件名
</th>
<th
width
=
"15%"
>
文件类型
</th>
<th
width
=
"15%"
>
文件大小
</th>
<th
width
=
"20%"
>
上传进度
</th>
<th
width
=
"15%"
>
<input
type
=
"button"
id
=
"upload-all-btn"
value
=
"全部上传"
>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<!-- 上传文件列表中每个文件的信息模版 -->
|
这里一并将CSS样式扔出来
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
body
{
font-family
:
Arial
;
}
form
{
margin
:
50px
auto
;
width
:
600px
;
}
input[type="button"]
{
cursor
:
pointer
;
}
table
{
display
:
none
;
margin-top
:
15px
;
border
:
1px
solid
#ddd
;
border-collapse
:
collapse
;
}
table th
{
color
:
#666
;
}
table td, table th
{
padding
:
5px
;
border
:
1px
solid
#ddd
;
text-align
:
center
;
font-size
:
14px
;
}
|
(2)接下来是JS的实现解析
通过FileList对象我们能获取到文件的一些信息
其中的size就是文件的大小,文件的分分割分片需要依赖这个
这里的size是字节数,所以在界面显示文件大小时,可以这样转化
1
2
3
4
5
6
7
8
|
// 计算文件大小
size
=
file
.
size
>
1024
?
file
.
size
/
1024
>
1024
?
file
.
size
/
(
1024
*
1024
)
>
1024
?
(
file
.
size
/
(
1024
*
1024
*
1024
)
)
.
toFixed
(
2
)
+
'GB'
:
(
file
.
size
/
(
1024
*
1024
)
)
.
toFixed
(
2
)
+
'MB'
:
(
file
.
size
/
1024
)
.
toFixed
(
2
)
+
'KB'
:
(
file
.
size
)
.
toFixed
(
2
)
+
'B'
;
|
选择文件后显示文件的信息,在模版中替换一下数据
1
2
3
4
5
6
7
8
9
|
// 更新文件信息列表
uploadItem
.
push
(
uploadItemTpl
.
replace
(
/{
{fileName}}/g
,
file
.
name
)
.
replace
(
'{
{fileType}}'
,
file
.
type
||
file
.
name
.
match
(
/
\
.
\
w
+
$
/
)
+
'文件'
)
.
replace
(
'{
{fileSize}}'
,
size
)
.
replace
(
'{
{progress}}'
,
progress
)
.
replace
(
'{
{totalSize}}'
,
file
.
size
)
.
replace
(
'{
{uploadVal}}'
,
uploadVal
)
)
;
|
不过,在显示文件信息的时候,可能这个文件之前之前已经上传过了,为了断点续传,需要判断并在界面上做出提示
通过查询本地看是否有相应的数据(这里的做法是当本地记录的是已经上传100%时,就直接是重新上传而不是继续上传了)
1
2
3
4
5
6
7
|
// 初始通过本地记录,判断该文件是否曾经上传过
percent
=
window
.
localStorage
.
getItem
(
file
.
name
+
'_p'
)
;
if
(
percent
&&
percent
!==
'100.0'
)
{
progress
=
'已上传 '
+
percent
+
'%'
;
uploadVal
=
'继续上传'
;
}
|
显示了文件信息列表
点击开始上传,可以上传相应的文件
上传文件的时候需要就将文件进行分片分段
比如这里配置的每段1024B,总共chunks段(用来判断是否为末段),第chunk段,当前已上传的百分比percent等
需要提一下的是这个暂停上传的操作,其实我还没实现出来,暂停不了无奈ing…
接下来是分段过程
1
2
3
4
5
6
7
8
9
10
11
12
</
|