127 lines
3.0 KiB
JavaScript
127 lines
3.0 KiB
JavaScript
import userApi from '../../api/user';
|
||
|
||
Component({
|
||
|
||
/**
|
||
* 组件的属性列表
|
||
*/
|
||
properties: {
|
||
loading:{
|
||
type:Boolean,
|
||
value:false
|
||
},
|
||
maxImgCount:{
|
||
type:Number,
|
||
value:10
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 组件的初始数据
|
||
*/
|
||
data: {
|
||
tempImgs:[]
|
||
},
|
||
|
||
/**
|
||
* 组件的方法列表
|
||
*/
|
||
methods: {
|
||
chooseImage(){
|
||
wx.chooseMedia({
|
||
count:this.properties.maxImgCount - this.data.tempImgs.length,
|
||
mediaType:['image'],
|
||
sourceType:['camera'],
|
||
success:(res)=>{
|
||
this.setData({
|
||
tempImgs:this.data.tempImgs.concat(res.tempFiles)
|
||
});
|
||
this.uploadImages();
|
||
}
|
||
});
|
||
},
|
||
async uploadImages(){
|
||
let imgIndex = -1;
|
||
const file = this.data.tempImgs.find((item,index)=>{
|
||
imgIndex = index;
|
||
return !item.uploaded;
|
||
});
|
||
if(!file){
|
||
this.setData({
|
||
loading:false
|
||
})
|
||
return;
|
||
}
|
||
this.setData({
|
||
loading:true
|
||
})
|
||
let onProgress = (res)=>{
|
||
//进度
|
||
this.setData({
|
||
[`tempImgs[${imgIndex}].progress`]:res.progress
|
||
})
|
||
}
|
||
//无奈之举,不大范围改动代码的同时,我需要获取到上传任务task,来中断上传操作,不然要出问题task在上传时被附加到了onProgress
|
||
this.data.tempImgs[imgIndex].onProgress = onProgress;
|
||
let uploadResult = {};
|
||
try {
|
||
// uploadResult = await userApi.uploadImg({tempFilePath:'123'},onProgress);
|
||
uploadResult = await userApi.uploadImg(file,onProgress);
|
||
} catch (error) {
|
||
//这里要死循环
|
||
// await this.uploadImages();
|
||
// return;
|
||
}
|
||
if(uploadResult.url){
|
||
this.setData({
|
||
[`tempImgs[${imgIndex}].uploaded`]:true,
|
||
[`tempImgs[${imgIndex}].serverUrl`]:uploadResult.url
|
||
})
|
||
await this.uploadImages();
|
||
}else{
|
||
//上传失败
|
||
this.setData({
|
||
loading:false
|
||
})
|
||
wx.showToast({
|
||
icon:'error',
|
||
title: '上传失败',
|
||
})
|
||
return new Error('失败')
|
||
}
|
||
},
|
||
removeImage(event){
|
||
const index = event.currentTarget.dataset.index;
|
||
if(this.data.tempImgs[index].onProgress&&this.data.tempImgs[index].onProgress.task){
|
||
this.data.tempImgs[index].onProgress.task.abort();
|
||
}
|
||
console.log('remove',new Date().getTime());
|
||
this.data.tempImgs.splice(index,1);
|
||
this.setData({
|
||
tempImgs:this.data.tempImgs
|
||
});
|
||
},
|
||
async getUploadedUrl(){
|
||
await this.uploadImages();
|
||
let urls = [],loadAll = true;
|
||
this.data.tempImgs.map((item)=>{
|
||
if(!item.uploaded)loadAll = false;
|
||
urls.push(item.serverUrl);
|
||
})
|
||
if(loadAll){
|
||
return urls
|
||
}
|
||
throw new Error('图片上传失败');
|
||
},
|
||
setUploadedImgs(imgs){
|
||
this.setData({
|
||
tempImgs:imgs
|
||
})
|
||
}
|
||
},
|
||
lifetimes:{
|
||
attached(){
|
||
console.log('img uploader init');
|
||
}
|
||
}
|
||
}) |