微信小程序项目开发总结-bjh

一.封装接口

/**
 * 请求头
 */
var header = {
  'content-type': 'application/x-www-form-urlencoded',
  'Authorization': "Bearer " + wx.getStorageSync("token"),
  'os': 'android',
  'version': '1.0.0',
  'device_token': 'ebc9f523e570ef14',
}

/**
 * 供外部post请求调用  
 */
function post(url, params, onSuccess, onFailed) {
  console.log("请求方式:", "POST")
  request(url, params, "POST", onSuccess, onFailed);

}

/**
 * 供外部get请求调用
 */
function get(url, params, onSuccess, onFailed) {
  console.log("请求方式:", "GET")
  request(url, params, "GET", onSuccess, onFailed);
}

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式:GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */

function request(url, params, method, onSuccess, onFailed) {
  console.log('请求url:' + url);
  wx.showLoading({
    title: "正在加载中...",
  })
  console.log("请求头:", header)
  wx.request({
    url: url,
    data: dealParams(params),
    method: method,
    header: header,
    success: function(res) {
      wx.hideLoading();
      console.log('响应:', res.data);

      if (res.data) {
        /** start 根据需求 接口的返回状态码进行处理 */
        if (res.statusCode == 200) {
          onSuccess(res.data); //request success
        } else {
          onFailed(res.data.message); //request failed
        }
        /** end 处理结束*/
      }
    },
    fail: function(error) {
      onFailed(""); //failure for other reasons
    }
  })
}

/**
 * function: 根据需求处理请求参数:添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  console.log("请求参数:", params)
  return params;
}


// 1.通过module.exports方式提供给外部调用
module.exports = {
  postRequest: post,
  getRequest: get,
}

二.上传图片 并压缩图片

1.wxml

   <canvas style="width: {{cw0}}px; height: {{ch0}}px;position: absolute; z-index: -1; left: -10000rpx;; top: -10000rpx;" canvas-id="myCanvas0"></canvas>

2.wxjs

    cw0: '',
    ch0: '',
    scale:0.1,


  compress: function (e) {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success(res) {
        let path = res.tempFilePaths[0];
        let size = res.tempFiles[0].size / 1024;
        if (size > 1000) { //大于100k压缩
          wx.getImageInfo({
            src: path,
            success(res) {
              //console.log('获得原始图片大小',res.width)
              let originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              let maxWidth = originWidth * that.data.scale,
                maxHeight = originHeight * that.data.scale;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              //等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }
              //更新canvas大小
              that.setData({
                cw0: targetWidth,
                ch0: targetHeight
              });
              let id = "myCanvas0";
              //尝试压缩文件,创建 canvas
              let ctx = wx.createCanvasContext(id);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(path, 0, 0, targetWidth, targetHeight);
              ctx.draw();
              wx.showLoading({
                title: "压缩中..."
              })
              //保存图片
              setTimeout(function () {
                wx.canvasToTempFilePath({
                  fileType: "jpg",
                  canvasId: id,
                  success: (res) => {
                    //写入图片数组
                    let uploadFile = res.tempFilePath;
                    that.uploadImg(uploadFile);

                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              }, 500);
            }
          })
        } else {
          wx.showLoading({
            title: "保存中..."
          })
          that.uploadImg(path);
        }
      }
    })
  },
  uploadImg: function (imgPath) {
    this.setData({
      imags: imgPath
    })

    let that = this

    // 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
    wx.uploadFile({
      url: httpname.domainName + api.UploadPic, // 仅为示例,非真实的接口地址
      filePath: imgPath,
      // sizeType: 'compressed',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        token: wx.getStorageSync('usertoke').token
      },
      name: 'img',
      formData: {
        uid: wx.getStorageSync('usertoke').uid,
        flag: 5
      },
      success(res) {
    
        wx.hideLoading()
        let data = JSON.parse(res.data)
        let list = that.data.fileList
        list.push(data.result.url)

        that.setData({ fileList: list });
        // 上传完成需要更新 fileList
      },
    });
  },

三.预览图片

wx.previewImage({
  urls: ["http://122.114.165.96:9994/c4272ff126757a788a05144c0f115943.png"]
})

四.微信小程序生成二维码

 onShow: function() {
 2 
 3    4 
 5     let _this = this;
 6     wx.request({
 7       url: 'https://api.weixin.qq.com/cgi-bin/token',
 8       data: {
 9         grant_type: 'client_credential',
10         appid: '填写appid', //不能缺少
11         secret: '填写app秘钥' //不能缺少
12       },
13       success: function(res) {
14 
15         wx.request({
16           url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + res.data.access_token,
17           data: {
18             // "path": "pages/index/index", 默认跳转到主页:pages/index/index,可指定
19             "width": 430,
20             "scene": wx.getStorageSync('uid')
21           },
22           responseType: 'arraybuffer', // 这行很重要,转为二进制数组
23           header: {
24             'content-type': 'application/json;charset=utf-8'
25           },
26           method: 'POST',
27           success(res) {
28             //转为base64
29             let bin64 = wx.arrayBufferToBase64(res.data);
30 
31             _this.setData({
32           //base 64设置到页面上
33               img: "data:image/png;base64," + bin64
34             });
35           }
36         })
37       }
38     })
39   },


 五.base64格式的小程序码通过canvas画出来无效(转本地路径)
// 把小程序码写入本地
export const writeFile = (base64Str => {
  return new Promise((resolve,reject)=>{
    // 后台返回的base64格式数据的回车换行换为空字符''
    let base64Image =  base64Str.split(',')[1].replace(/[\r\n]/g, '');
    // 文件管理器
    const fsm = wx.getFileSystemManager();
    // 文件名
    const FILE_BASE_NAME = 'tmp_base64src';
    // 文件后缀
    const format = 'png';
    // 获取当前时间戳用于区分小程序码,防止多次写进的小程序码图片都一样,建议通过不同的列表ID来区分不同的小程序码
    const timestamp = (new Date()).getTime();
    // base转二进制
    const buffer = wx.base64ToArrayBuffer(base64Image),
    // 文件名
    filePath = `${wx.env.USER_DATA_PATH}/${timestamp}share.${format}`;
    // 写文件
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success(res) {
        // 读取图片
        wx.getImageInfo({
          src: filePath,
          success: function(res) {
            let img = res.path;
            // 把需要画出来的图片的临时url暴露出去
            resolve(img);
            reject();
          },
          fail(e){
            console.log('读取图片报错');
            console.log(e);
          },
          error(res) {
            console.log(res)
          }
        })
      },
      fail(e){
        console.log(e);
      }
    })
  }).catch((e) => {
    console.log(e);
  })
});

// 删除存储的垃圾数据
export const removeSave = () =>{
  return new Promise((resolve)=>{
    // 文件管理器
    const fsm = wx.getFileSystemManager();
    // 获取文件列表
    fsm.readdir({
      dirPath: wx.env.USER_DATA_PATH, // 当时写入的文件夹
      success(res){
        res.files.forEach((el) => { // 遍历文件列表里的数据
          // 删除存储的垃圾数据
          if (el !== 'miniprogramLog') { // 过滤掉miniprogramLog
            fsm.unlink({
              filePath: `${wx.env.USER_DATA_PATH}/${el}`, // 文件夹也要加上,如果直接文件名会无法找到这个文件
              fail(e){
                console.log('readdir文件删除失败:', e)
              }
            });
          }
        })
        resolve()
      }
    })
  })
}



// 在页面调用方法
import { writeFile } from '../../utils/wxFunc'
 
removeBeforeFiles () {
  removeSave().then(() => {
    this.getUseCode();
  }).catch(e => {
    console.log(e);
  })
},
 
getUseCode () {
  writeFile(codeUrl).then(img => { // codeUrl为base64格式的小程序码
    this.createCanvas(img);
  }).catch(e => {
    console.log(e);
  })

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值