美文网首页
小程序之图片上传接口封装

小程序之图片上传接口封装

作者: 白衣诗人 | 来源:发表于2021-02-01 15:21 被阅读0次

用到的知识点

1、wx.chooseImage,https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
2、Promise,Promise 对象有以下两个特点:对象的状态不受外界影响。Promise 对象代表一个异步操作,有三种状态:pending: 初始状态,不是成功或失败状态。fulfilled: 意味着操作成功完成。rejected: 意味着操作失败。

下面是示例源码

/**
   * 图片上传
   * @param {*} all 一共可以上传的长度
   * @param {*} length 已经上传存在的图片长度
   */
  getFeilUpload:function(all,length){
    let _this = this;
    let count = 1;
    count = all - length;
    console.log(all, length)
    return new Promise(function(resolve, reject){
      if(count>0){
        wx.chooseImage({
          count: count,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success (res) {
            // tempFilePath可以作为img标签的src属性显示图片
            const tempFilePaths = res.tempFilePaths;
            for(let i=0;i<tempFilePaths.length;i++){
              wx.showLoading();
              wx.uploadFile({
                url: http+'api/common/upload', //http为接口链接地址  仅为示例,非真实的接口地址
                filePath: res.tempFilePaths[i],
                name: 'file',
                success (res){
                  console.log(res)
                  wx.hideLoading({})
                  if(res.statusCode == 200){
                    let data = JSON.parse(res.data);
                    resolve(JSON.parse(res.data))
                  }else{
                    reject(res.data)
                    wx.showToast({
                      title: '图片上传失败',
                      icon:'none'
                    })
                  }
                },
                fail:function(err){
                  wx.hideLoading();
                }
              })
            }
          }
        })
      }else{
        wx.showToast({
          title: '最多可上传'+all+"张图片",
          icon:'none'
        })
      }
    }) 
  }

使用

引入路径.getFeilUpload(1,0).then(function(res){
    成功返回
}).catch(function(){
  失败返回
});

使用说明

getFeilUpload(),可以放在小程序启动页app.js里面。也可以重新生成一个js页面。在需要引用的页面引入,如果是放在app.js里面的,在其他页面引入为 const app = getApp();,使用时 app.getFeilUpload(1,0); 如果是一个新的js页面。则按照小程序的引入规则引入。使用方法是差不多的。

相关文章

网友评论

      本文标题:小程序之图片上传接口封装

      本文链接:https://www.haomeiwen.com/subject/xsojtltx.html