使用Promise实现同步处理
<div>
<input type="file" accept="image/*" @change="setImage" multiple="multiple"/>
</div>
<script>
setImage(e) {
let that = this
const files = e.target.files;
that.checkIsImage(files)
.then(that.readerFileToList)
}).then(function(){
return new Promise(function(resolve, reject){
// do sth for upload
ajax.post ...
})
}).catch(error => that.$Message.error(error))
},
/**
* 检查是否图片格式
* @param files
*/
checkIsImage(files){
return new Promise(function(resolve, reject){
let fileLength = 0;
let checkImage = function(file){
if (!file.type.includes('image/')) {
let error = '请选择图片'
reject(error)
}
fileLength++
if(fileLength<files.length){
checkImage(files[fileLength])
}else{
resolve(files)
}
}
checkImage(files[fileLength])
})
},
/**
* 读取图片到数组
* @param files
*/
readerFileToList(files){
return new Promise(function(resolve, reject){
if (typeof FileReader === 'function') {
let uploadList = []
let fileLength = 0;
const reader = new FileReader();
reader.readAsDataURL(files[fileLength]);
reader.onload = function(e) {
if(e.target.result) {
uploadList.push(e.target.result)
fileLength++;
if(fileLength < files.length) {
reader.readAsDataURL(files[fileLength]);
} else {
resolve(uploadList)
}
}
}
}else{
let error = 'FileReader API不支持'
reject(error)
}
})
},
</script>
多张网络图片转base64
let srcs = ['http://xxx.png','http://xxx.png']
this.readerImageSrcToBase64(srcs)
.then( e=> {
// 处理base64数组
})
/**
* 将图片url转base64读取到数组
* @param srcs
*/
readerImageSrcToBase64(srcs){
return new Promise(function(resolve, reject){
function getBase64Image(img) {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
let dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
let imgBase64List = []
let index = 0;
let image = new Image();
image.crossOrigin = '';
image.src = srcs[index];
image.onload = function(){
let base64 = getBase64Image(image);
imgBase64List.push(base64)
index++;
if(index < srcs.length) {
image.src = srcs[index];
} else {
resolve(imgBase64List)
}
}
})
},