mini/miniprogram_npm/@beefast-wxmp/img-uploader/index.js
2025-04-13 01:27:54 +08:00

125 lines
2.7 KiB
JavaScript

Component({
/**
* 组件的属性列表
*/
properties: {
loading:{
type:Boolean,
value:false
},
maxImgCount:{
type:Number,
value:10
},
/**
* url:上传地址
* header:{}
*/
options:Object
},
/**
* 组件的初始数据
*/
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.triggerEvent('imgChange',this.data.tempImgs);
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
})
const task = wx.uploadFile({
filePath: file.tempFilePath,
name: 'file',
header:this.properties.options.header||{},
url: this.properties.options.url,
success:(res)=>{
const response = JSON.parse(res.data);
this.setData({
[`tempImgs[${imgIndex}].uploaded`]:true,
[`tempImgs[${imgIndex}].serverUrl`]:response.data.url
})
this.uploadImages();
},
fail:(res)=>{
this.setData({
loading:false
})
wx.showToast({
icon:'error',
title: '上传失败',
})
}
});
file.task = task;
task.onProgressUpdate((res)=>{
this.setData({
[`tempImgs[${imgIndex}].progress`]:res.progress
})
})
},
removeImage(event){
const index = event.currentTarget.dataset.index;
if(this.data.tempImgs[index].task){
this.data.tempImgs[index].task.abort();
}
this.data.tempImgs.splice(index,1);
this.setData({
tempImgs:this.data.tempImgs
});
this.triggerEvent('imgChange',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(){
}
}
})