微信JSSDK上传图片功能

1、公众号开发集成微信JSSDK
  • 登录公众平台
  • 下载TXT文件放到域名根目录下
  • 加入js安全域名
2、配置wxsdk集成到项目中
import wx from 'weixin-js-sdk';
// 生成签名
import { getWxSignature } from './../../api/member/commonApi';
const wxsdk = {
  /**
   * @param {*} callback 回调函数
   */
otherInit(type, callback, value) {
    let url = window.location.href;
    let appid = 'appid';
    let link = window.location.href;
    // hash模式的单页应用这样处理,否则会签名失败。history模式不需要这样处理
    link = window.location.href.split('#')[0];
    let params = {
      url: link,
    };
    getWxSignature(params).then(res => {
      if (res && res.data && !res.data.error) {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId: appid, // 必填,公众号的唯一标识
          timestamp: res.data.timestamp, // 必填,生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
          signature: res.data.signature, // 必填,签名
          jsApiList: [
            'chooseImage',
            'uploadImage',
            'downloadImage',
            'getLocalImgData',
          ], // 必填,需要使用的JS接口列表
        });
        wx.ready(function() {
          if (type == 'chooseImage') {
            wxsdk.chooseImage(callback, value);
          }
        });
        wx.error(function() {});
      }
    });
  },
   chooseImage(callback, type) {
    wx.checkJsApi({
      jsApiList: ['chooseImage'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
      success: function(res) {
        if (res.checkResult.chooseImage) {
          if (type == '1') {
            wx.chooseImage({
              count: 1, // 默认9
              sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
              sourceType: ['album'], // 可以指定来源是相册还是相机,默认二者都有
              success: function(res) {
                var localIds = res.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                wxsdk.wxBaseImage(localIds, callback);
              },
              cancel: function(res) {
                if (callback) {
                  callback('');
                }
              },
            });
          } else if (type == '2') {
            wx.chooseImage({
              count: 1, // 默认9
              sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
              sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
              success: function(res) {
                var localIds = res.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                wxsdk.wxBaseImage(localIds, callback);
              },
              cancel: function(res) {
                if (callback) {
                  callback('');
                }
              },
            });
          } else if (type == '3') {
            wx.chooseImage({
              count: 1, // 默认9
              sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
              sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
              success: function(res) {
                var localIds = res.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                wxsdk.wxBaseImage(localIds, callback);
              },
              cancel: function(res) {
                if (callback) {
                  callback('');
                }
              },
            });
          }
        }
      },
    });
  },
  wxBaseImage(localIds, callback) {
    wx.uploadImage({
      localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
      isShowProgressTips: 1, // 默认为1,显示进度提示
      success: function(res) {
        var serverId = res.serverId; // 返回图片的服务器端ID
        wx.downloadImage({
          serverId: serverId, // 需要下载的图片的服务器端ID,由uploadImage接口获得
          isShowProgressTips: 1, // 默认为1,显示进度提示
          success: function(res) {
            var localId = res.localId; // 返回图片下载后的本地ID
            wx.getLocalImgData({
              localId: localId, // 图片的localID
              success: function(res) {
                var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
                if (callback) {
                  callback(res);
                }
              },
            });
          },
        });
      },
    });
  },
 }
export wxsdk
3、项目中使用拍照上传功能
  • 引入wxsdk
import wxsdk from './../../../../common/js/wxsdk';
  • 调用上传图片方法
chooseImage = value => {
    wxsdk.otherInit('chooseImage', this.triggerChooseImage, value);
  };
triggerChooseImage = res => {
	// res是微信返回的base64的图片(这里需要注意的是,ios和安卓返回的格式不一样),安卓的返回前面没有data:image/jpeg;base64,前缀并且后面的字符串中包含换行符,ios的返回结果中data:image/jgp需要替换成data:image/jpeg
    let baseImage = res.localData;
    if (baseImage.indexOf('data:image') != 0) {
      //判断是否有这样的头部
      baseImage = 'data:image/jpeg;base64,' + baseImage;
    }
    baseImage = baseImage
      .replace(/\r|\n/g, '')
      .replace('data:image/jgp', 'data:image/jpeg');
    //调用
    var blob = this.dataURLtoBlob(baseImage);
    var file = this.blobToFile(blob, 'shangchauan.jpg');
    console.log(file);
    const params = new FormData();
    params.append('file', file);
    // 上传图片的接口
    uploadimg(params).then(res => {
      if (res.status == 200) {
        console.log(res.data.url);
        this.setState({
          wxImage: res.data.url,
        });
      }
    });
  };
  //将base64转换为blob
  dataURLtoBlob = dataurl => {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  };
  //将blob转换为file
  blobToFile = (theBlob, fileName) => {
    let options = {
      lastModifiedDate: new Date(),
      lastModified: new Date().getTime(),
      type: 'image/png',
      uid: this.getUuid(),
      webkitRelativePath: '',
    };
    // File()前两个参数是必填参数,options是选填参数
    let file = new window.File([theBlob], fileName, options);
    return file;
  };
  getUuid = () => {
    var s = [];
    var hexDigits = '0123456789abcdef';
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-';

    var uuid = s.join('');
    return uuid;
  };
坑点总结
  • 1、调用wx.getLocalImgData()失败
    原因:上传的是单张图片在wx.chooseImage()取得var localIds = res.localIds------>需要替换成var localIds = res.localIds[0];
  • 2、不清楚ios与安卓的兼容性问题
  • 3、base64转换为Blob对象
  • 4、调用后台接口需要上传File类型,需要将Blob转换为File对象(ps:网上有很多不正确的方法)
    建议用这个:
/**
   * @param {*} theBlob 图片的Blob对象-必传参数
   * @param {*} theBlob 图片的文件名-必传参数
   * @param {*} theBlob file对象的其他参数-非必传参数
   */
blobToFile = (theBlob, fileName) => {
    let options = {
      lastModifiedDate: new Date(),
      lastModified: new Date().getTime(),
      type: 'image/png',
      uid: this.getUuid(),
      webkitRelativePath: '',
    };
    let file = new window.File([theBlob], fileName, options);
    return file;
  };
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值