温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

微信小程序中怎么封装多张图片上传api

发布时间:2022-04-13 14:56:33 来源:亿速云 阅读:207 作者:iii 栏目:编程语言

本篇内容介绍了“微信小程序中怎么封装多张图片上传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”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI