参数
{
sourceType:['album', 'camera'], // 选择图片方式, album 从相册选图,camera 使用相机,默认二者都有
sizeType: ['original', 'compressed'], //是否压缩,original 原图,compressed 压缩图,默认二者都有
count: 1, //选择图片张数,默认1
size: 2, //图片大小限制,2为2M
type: 'goods', // 表示上传的种类,方便回调区分
upload: true // 是否上传 ,上传页面后自动调页面 mulImgUploadSuccess方法,有 上传后 图片arr数组 以及你传入的type 两个参数
}
let uploadImg = ‘上传地址’
choseImg(obj) {
if(!obj){obj = {}}
obj.sourceType ? '' : obj.sourceType = ['album', 'camera']
obj.sizeType ? '' : obj.sizeType = ['original', 'compressed']
obj.count ? '' : obj.count = 1
let pages = getCurrentPages(),
current = pages[pages.length - 1];
return new Promise((resolve, reject) => {
if (current.data.choosingImg) {
reject("重复点击")
return
}else{
current.setData({ choosingImg: true })
}
wx.chooseImage({
count: obj.count,
sizeType: obj.sizeType, // original 原图,compressed 压缩图,默认二者都有
sourceType: obj.sourceType, // album 从相册选图,camera 使用相机,默认二者都有
success: (res)=> {
if (obj.size) {
let ifsize = true
res.tempFiles.forEach(el => {
console.log(el.size / 1024 / 1204 > obj.size)
if (el.size / 1024 / 1204 > obj.size) {
ifsize = false
}
})
if (!ifsize) {
wx.showToast({
title: '图片大小不能超过' + obj.size + 'M',
duration: 2000,
icon: 'none'
})
reject('image to large')
return
}
}
if(obj.upload){
this.uploadImgArr(res.tempFilePaths,obj.type)
}
resolve(res)
},
fail: (e => {
reject(e)
}),
complete: () => {
current.setData({ choosingImg: false })
}
})
})
}
// 多图上传
uploadImgArr(arr, type = '') {
if (!arr || arr.length == 0) { return }
this.getImgArr = [],
this.nowIndex = 0;
this.handleImgList(0, arr, type)
wx.showLoading({
title: '开始上传',
mask: true
})
}
handleImgList(index, arr, type) {
let pages = getCurrentPages(),
current = pages[pages.length - 1];
if (!arr[index]) {
wx.hideLoading()
return
}
// 上传图片函数onlyUploadImg
this.onlyUploadImg(arr[index], type, true).then(res => {
this.getImgArr.push(res)
if (arr[++index]) {
wx.showLoading({
title: '正在上传:' + index + '/' + arr.length,
mask: true
})
this.nowIndex = index
this.handleImgList(index, arr, type)
} else {
current.mulImgUploadSuccess ? current.mulImgUploadSuccess(this.getImgArr,type) : ''
wx.hideLoading()
}
}).catch(e => {
current.mulImgUploadFail ? current.mulImgUploadFail(e) : ''
wx.hideLoading()
})
}
// 图片上传
onlyUploadImg(url, types, noLoading) {
if (!url) {
console.warn('no upload url')
return
}
return new Promise((resolve, reject) => {
if (!noLoading) {
wx.showLoading({
title: '上传中',
mask: true
})
}
wx.uploadFile({
url: uploadImg,
filePath: url,
name: 'file',
formData: {
'type': types ? types : ""
},
success: (res => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
if (this._errorHandler != null) {
this._errorHandler(res)
}
reject(res)
}
}),
fail: (e=>{
wx.showToast({ title: "上传失败", icon: 'none' })
}),
complete: (res => {
if (!noLoading) {
wx.hideLoading();
}
})
})
})
}