小程序公共方法及请求封装-图片视频上传

⭐ 小程序公共方法及请求封装


app.js


/**
 * app.js
 * author: J1ay
 * 小程序部分公共方法封装
**/

App({
  onLaunch() {
   	// wx.getUpdateManager 在 1.9.90 才可用,请注意兼容
		const updateManager = wx.getUpdateManager()
		updateManager.onCheckForUpdate(function (res) {
			// 请求完新版本信息的回调
			// console.log(res.hasUpdate)
		})
		updateManager.onUpdateReady(function () {
			wx.showModal({
				title: '更新提示',
				content: '新版本已经准备好,是否马上重启小程序?',
				success: function (res) {
					if (res.confirm) {
						// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate()
					}
				}
			})
		})
		updateManager.onUpdateFailed(function () {
			// 新的版本下载失败
		})
  },

  // 正则表达式封装
  regExps: {
    email: /^[0-9a-zA-Z_]+@[0-9a-zA-Z_]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$/,    //邮箱
    phone: /^(?:1\d{2})-?\d{5}(\d{3}|\*{3})$/,    //手机号码
  },

  // 七牛云上传多张图片 默认上传图片 type = 1 视频
  qiniuToUpload(type, callFn){
    let that = this
    that.request('get', '/shifu/index/api_upload_qiniu_get_token', {}, function (res) {
      if (res.error_code == 0) {
        that.globalData.upload_host = res.data.upload_host
        that.globalData.img_domain = res.data.host 
        that.uploadFile(res.data.token, type, callFn)
      } else {
        wx.showToast({
          title: res.error_message,
          icon: 'none'
        })
      }
    }, (err) => {})
  },

  // 上传 默认上传图片; type = 1 是视频
  uploadFile(token, type, callFn) {
    let that = this
    if (type == 1) {
      wx.chooseVideo({
        success(res) {
          const tempFilePaths = res.tempFilePath
          wx.showLoading({
            title: '拼命上传中',
          })
          wx.uploadFile({
            url: that.globalData.upload_host,
            filePath: tempFilePaths,
            name: 'file',
            formData: {
              'token': that.data.token
            },
            success(res) {
              const data = JSON.parse(res.data)
              callFn && callFn(data);
            },
            fail: (res) => {
              wx.showToast({
                title: res.errMsg,
                icon: 'none'
              })
            },
            complete() {
              wx.hideLoading()
            }
          })
        }
      })
    }
    else {
      wx.chooseImage({
        count: 9,
        success(res) {
          console.log(res)
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          wx.showLoading({
            title: '拼命上传中',
          })
          for (let i = 0; i < tempFilePaths.length; i++) {
            wx.uploadFile({
              url: that.globalData.upload_host,
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                'token': token,
              },
              success(res) {
                console.log(res)
                const data = JSON.parse(res.data)
                callFn && callFn(data);
              },
              fail: (res) => {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none'
                })
              },
              complete() {
                if (i == tempFilePaths.length - 1) {
                  wx.hideLoading()
                }
              }
            })
          }
        }
      })
    }
  },


  // 请求方法封装
  request(type,url,obj,callback) {
    wx.showLoading({
      title: '拼命加载中',
    })
    let that = this
    let openid = wx.getStorageSync('openid') ? wx.getStorageSync('openid'): that.globalData.openid;
    let appid =  that.globalData.appid
    // 不是登录接口
    if(url!='/api/login') {
      // 视接口所需参数而定
      obj=Object.assign(obj,{'openid':openid});
      obj=Object.assign(obj,{'appid':appid});
    }
    let param=obj;
    wx.request({
      method: type,
      dataType: 'json',
      url: that.globalData.requestUrl + url,
      data: param,
      header: {
        'content-type': 'application/json',
      },
      success: function (res) {
        callback(res.data);
      },
      complete: function() {
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },
  globalData: {
    openid: '', //登录凭证
    appid: '', // 小程序
    requestUrl: '', // 请求地址
    upload_host: '', // 七牛云上传地址
    img_domain: '' // 文件路径前缀
  }
})


util.js


日期格式转换


/**
 * /utils/util.js
 * author: J1ay
 * 日期格式转换
**/

// 日期转换 视自己情况而定
// 默认: yyyy/mm/dd/ hh:mm:ss
// 1: yyyy-mm-dd
// 2: yyyy-mm-dd hh:mm
const formatTime = (date,type) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  if (type == 1) {
    return `${[year, month, day].map(formatNumber).join('-')}`
  }
  else if (type == 2) {
    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute].map(formatNumber).join(':')}`
  }
  else {
     return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
  }
}
 
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime
}


使用示例


/**
 * index.js
 * author: J1ay
 * 公共方法使用示例
**/

let app = getApp()
let utils = require("../../utils/util")

Page({
  data: {

  },
  onLoad: function (options) {
      // 请求方法
      app.request('get/post 请求方法','接口请求地址', {xxx:yy (请求参数,可以为空)}, function(res){
          console.log(res)
      })
      //如:
      app.request('post','/api/getUserInfo', {}, function(res){
          console.log(res)
      })
      // 测试手机号格式
      console.log(app.regExps.phone.test("13605862404"))
      // 转换日期格式
      console.log(utils.formatTime(new Date(), 1))
      
      // 上传图片
      app.qiniuToUpload(0,function(res){
          console.log(res)
      })
  },
})

小程序公共方法请求封装下载地址


将不定期补充更新~


posted @ 2021-09-07 11:02  J1ay  阅读(173)  评论(0编辑  收藏  举报