參數
{
sourceType:['album', 'camera'], // 選擇圖片方式, album 從相冊選圖,camera 使用相機,默認兩者都有
sizeType: ['original', 'compressed'], //是否壓縮,original 原圖,compressed 壓縮圖,默認兩者都有
count: 1, //選擇圖片張數,默認1
size: 2, //圖片大小限制,2爲2M
type: 'goods', // 表示上傳的種類,方便回調區分,跟圖片一塊兒傳到後臺
upload: true // 是否上傳 ,上傳頁面後自動調頁面 mulImgUploadSuccess方法,回調參數包含 圖片上傳返回的結果數組 以及你傳入的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();
}
})
})
})
}
複製代碼