<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<!-- multiple属性规定文件上传可以多选 -->
<input type="file" name="file" id="file" multiple>
<pre>
将上传的文件进行base64转码,并转换为JSON数据格式
(注意异步的问题)
</pre>
<script>
$("#file").change(function(){
var arr = [];
for(let i = 0;i<$(this)[0].files.length;i++){
arr.push($(this)[0].files[i]);
}
var arr2 = [];
arr.forEach((val,index)=>{
let reader = new FileReader();
reader.readAsDataURL(val);
reader.onload = function(e){
arr2.push(e.target.result);
if(arr2.length == arr.length){
console.log(JSON.stringify({files:arr2}));
}else{
console.log("不行");
}
}
})
var p = new Promise(function(resolve,reject){
var arr2 = [];
arr.forEach((val,index)=>{
let reader = new FileReader();
reader.readAsDataURL(val);
reader.onload = function(e){
arr2.push(e.target.result);
if(arr2.length == arr.length){
resolve(arr2);
}
}
})
})
p.then(function(res){
console.log(JSON.stringify({files:res}));
},function(error){
})
})
</script>
</body>
</html>