這篇文章給大家分享的是有關(guān)微信小程序中如何封裝多張圖片上傳api的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

代碼如下
export default class Upload{
constructor(object) {
this.obj = {
count:1,
sizeType:['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType:['album','camera'], // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有
}
if(Object.prototype.toString.call(object) === "[object Object]"){
Object.assign(this.obj, object);
}else{
uni.showToast({
title: '參數(shù)必須為對象',
icon:"icon",
duration: 2000
});
}
return this;
}
// 上傳圖片 返回一個圖片的數(shù)組集合
async uploadPic(){
let chooseImageResult = await this.chooseImage()
console.log("選擇圖片",chooseImageResult)
let imgArr = await chooseImageResult.tempFilePaths.map(async (item,index) => {
uni.showLoading({
title: `正在上傳第${index+1}張`
});
let uploadFileResult = await this.uploadFile(item)
console.log("上傳圖片過程",uploadFileResult)
return getApp().globalData.img_prefix + uploadFileResult.data.file.url;
})
return new Promise((resolve,reject) => {
Promise.all(imgArr).then((result)=>{
uni.hideLoading();
uni.showToast({
title: '上傳成功',
icon:"none",
duration: 2000
});
console.log("上傳圖片結(jié)果",result)
resolve(result)
})
})
}
uploadFile(file){
return new Promise((resolve, reject) => {
uni.uploadFile({
url: 'https://baidu.com/upload/', //此處是你自己上傳接口
filePath: file,
name: 'file',
success: function (res) {
var data = res.data;
resolve(JSON.parse(data))
},
fail: function (res) {
reject("上傳失敗")
},
complete: function (res) {
uni.hideToast();
}
})
})
}
chooseImage(){
return new Promise((resolve,reject) => {
uni.chooseImage({
count: this.obj.count,//1, // 默認(rèn)9
sizeType: this.obj.sizeType,//['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType: this.obj.sourceType,//['album','camera'], // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有
success: function (res) {
// console.log(res)
resolve(res)
},
fail:function(){
reject("選擇文件失敗")
}
})
})
}
}使用實(shí)例
let object = {
count:1,
sizeType:['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType:['album','camera'], // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有
}
let result = await new Upload(object).uploadPic();感謝各位的閱讀!關(guān)于“微信小程序中如何封裝多張圖片上傳api”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
分享題目:微信小程序中如何封裝多張圖片上傳api-創(chuàng)新互聯(lián)
URL標(biāo)題:http://chinadenli.net/article14/didgde.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、服務(wù)器托管、動態(tài)網(wǎng)站、微信小程序、軟件開發(fā)、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容