微信小程序封装多张图片上传api代码实例

这篇文章主要介绍了微信小程序封装多张图片上传api代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

export default class Upload{ constructor(object) { this.obj = { count:1, sizeType:['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType:['album','camera'], // 可以指定来源是相册还是相机,默认二者都有 } if(Object.prototype.toString.call(object) === "[object Object]"){ Object.assign(this.obj, object); }else{ uni.showToast({ title: '参数必须为对象', icon:"icon", duration: 2000 }); } return this; } // 上传图片 返回一个图片的数组集合 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("上传图片结果",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, // 默认9 sizeType: this.obj.sizeType,//['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: this.obj.sourceType,//['album','camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // console.log(res) resolve(res) }, fail:function(){ reject("选择文件失败") } }) }) } }

使用实例

let object = { count:1, sizeType:['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType:['album','camera'], // 可以指定来源是相册还是相机,默认二者都有 } let result = await new Upload(object).uploadPic();

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8f3f4b679ea98bebdd4a7acda37244e8.html