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

2022-10-09,,,,

这篇文章主要介绍了微信小程序封装多张图片上传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();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

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

下载本文的Word格式文档,以方便收藏与打印。