本文主要介绍南
京微信小程序开发封装多张图片上传api代码的示例。示例代码将详细介绍,对每个人的学习或工作都有一定的参考学习价值。有需要的朋友可以参考一下
代码如下
export default class Upload{
constructor(object) {
this.obj = {
count:1,
Sizetype: ['original ','compressed'], // you can specify whether it is an original graph or a compressed graph. Both are available by default
Sourcetype: ['album ','camera'], // you can specify whether the source is an album or a camera. Both are available by default
}
if(Object.prototype.toString.call(object) === "[object Object]"){
Object.assign(this.obj, object);
}else{
uni.showToast({
Title: 'parameter must be an object',
icon:"icon",
duration: 2000
});
}
return this;
}
//Upload image returns an array collection of images
async uploadPic(){
let chooseImageResult = await this.chooseImage()
console.log (chooseimageresult)
let imgArr = await chooseImageResult.tempFilePaths.map(async (item,index) => {
uni.showLoading({
Title:'uploading the ${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: 'upload succeeded',
icon:"none",
duration: 2000
});
console.log (upload picture result, result)
resolve(result)
})
})
}
uploadFile(file){
return new Promise((resolve, reject) => {
uni.uploadFile({
url: ' https://baidu.com/upload/ '// here is your own upload interface
filePath: file,
name: 'file',
success: function (res) {
var data = res.data;
resolve(JSON.parse(data))
},
fail: function (res) {
Reject ("upload failed")
},
complete: function (res) {
uni.hideToast();
}
})
})
}
chooseImage(){
return new Promise((resolve,reject) => {
uni.chooseImage({
count: this.obj.count , // 1, // default 9
sizeType: this.obj.sizeType , // ['original ','compressed'], // you can specify whether it is an original graph or a compressed graph. By default, there are both
sourceType: this.obj.sourceType , // ['album ','camera'], // you can specify whether the source is an album or a camera. By default, there are both
success: function (res) {
// console.log(res)
resolve(res)
},
fail:function(){
Reject ("failed to select file")
}
})
})
}
}
使用范例
let object = {
count:1,
Sizetype: ['original ','compressed'], // you can specify whether it is an original graph or a compressed graph. Both are available by default
Sourcetype: ['album ','camera'], // you can specify whether the source is an album or a camera. Both are available by default
}
let result = await new Upload(object).uploadPic();
以上是本文的全部内容,希望对您有所帮助,也希望对开发人员有更多的支持。