基于HTML5的多张图片上传
图片上传之前也有写过demo,不过是单张上传的,最近有个业务需求是需要多张上传的,于是乎从新改写了一下
HTML结构:
1
2
3
4
<div
class
=
"container"
>
<label>请选择一个图像文件:</label>
<input type=
"file"
id=
"file_input"
multiple/>
</div>
顺便说下这个上传的主要逻辑:
·用input标签并选择type=file,记得带上multiple,不然就只能单选图片了
·绑定好input的change时间,
·重点就是如何处理这个change事件了,使用H5新的FileReader接口读取文件并打成base64编码,之后的事就是与后端同学交互着玩啦
JS代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
window.onload =
function
(){
var
input = document.getElementById(
"file_input"
);
var
result,div;
if
(
typeof
FileReader===
'undefined'
){
result.innerHTML =
"抱歉,你的浏览器不支持 FileReader"
;
input.setAttribute(
'disabled'
,
'disabled'
);
}
else
{
input.addEventListener(
'change'
,readFile,
false
);
}<br>
//handler
function
readFile(){
for
(
var
i=0;i<
this
.files.length;i++){
if
(!input[
'value'
].match(/.jpg|.gif|.png|.bmp/i)){
//判断上传文件格式
return
alert(
"上传的图片格式不正确,请重新选择"
)<br> }
var
reader =
new
FileReader();
reader.readAsDataURL(
this
.files[i]);
reader.onload =
function
(e){
result =
'<div , Courier, monospace !important; border-radius: 0 !important; border: 0 !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; line-height: 1.8em !important; margin: 0 !important; outline: 0 !important; overflow: visible !important; padding: 0 !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; auto !important; box-sizing: content-box !important; min-height: inherit !important'>;
div = document.createElement(
'div'
);
div.innerHTML = result;
document.getElementById(
'body'
).appendChild(div);
//插入dom树 <br> }
}
}
}
上传多张图片难道就这样实现了吗0.0
然而并没有,这样只是将图片转换成base64编码后再前端显示,一刷新什么都没有
插入图片后,打开开发者工具看html结构是这样的
现实的做法是,我们在处理函数里将文件队列里的文件发送到后端,后端同学呢返回文件对应的MD5加密过文件和路径给前端,前端就拿着这个路径渲染到页面上。
之后再把MD5文件传回给后端,因为上传完后前端一般有删除图片的操作,回传目的就是告诉后端确认那些图片是我们想要的,后端存入数据库里。
说下用jquery如何交互吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function
readFile(){
var
fd =
new
FormData();
for
(
var
i=0;i<
this
.files.length;i++){
var
reader =
new
FileReader();
reader.readAsDataURL(
this
.files[i]);
fd.append(i,
this
.files[i]);<br> }
$.ajax({
url :
''
,
type :
'post'
,
data : fd,
success :
function
(data){
console.log(data)
}
})
}
FormData也是H5的新接口,用来模拟表单控件的提交,最大的好处呢就是可以提交二进制文件
然后success的回调里面我们拿回了想要的数据后呢,就可以将图片插进去页面啦,类似之前的做法~
上个效果图: