微信公眾號 wx.chooseImage拍照或從手機相冊中選圖接口


微信公眾號 wx.chooseImage拍照或從手機相冊中選圖接口 :

1、調用微信接口

  <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

2、通過config接口注入權限驗證配置

wx.config({
  debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。
  appId: '', // 必填,公眾號的唯一標識
  timestamp: , // 必填,生成簽名的時間戳
  nonceStr: '', // 必填,生成簽名的隨機串
  signature: '',// 必填,簽名
  jsApiList: [] // 必填,需要使用的JS接口列表
});

3、利用微信公眾號的wx.chooseImage

  // 選擇圖片
  chooseImage(urlParam, fileCode) {
    console.log('點擊點擊');
    const that = this;
    if (typeof window !== 'undefined') {
      wx.ready(() => {
        wx.chooseImage({
          count: 1, // 默認9
          sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
          sourceType: ['album'], // 可以指定來源是相冊還是相機,默認二者都有
          success(req) {
            // localIds 返回選定照片的本地ID列表,localId可以作為img標簽的src屬性顯示圖片
            wx.getLocalImgData({
              localId: req.localIds[0].toString(),
              success(res) {
                const { localData } = res;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                  // 蘋果的直接賦值,默認生成'data:image/jpeg;base64,'的頭部拼接
                  imageBase64 = localData;
                } else {
                  // 此處是安卓中的唯一得坑!在拼接前需要對localData進行換行符的全局替換
                  // 此時一個正常的base64圖片路徑就完美生成賦值到img的src中了
                  imageBase64 = `data:image/jpeg;base64,${localData.replace(/\n/g, '')}`;
                }

                // 重新賦值圖片
                const obj = {};
                obj[urlParam] = imageBase64;
                // 賦值圖片
                that.setState(obj);
                that.handleAvatar(that.dataURLtoBlob(imageBase64), fileCode);
              }
            });
          },
          fail() {
            Toast.show({
              type: 'text',
              text: '選擇圖片失敗!'
            });
          }
        });
      });
    }
  }

4、利用form表單上傳圖片

  // 上傳圖片
  handleAvatar(info, fileCode) {
    console.log('上傳圖片的fileCode===', fileCode);
    const { sessionKey, pictureUrl } = this.props.getImgListData;

    Toast.loading('Loading...', 30);
    // 創建FormData
    const form = info;
    const formData = new FormData();
    // 傳遞參數
    formData.append('file', form, 'test.jpg');
    formData.append('channelId', utils.channelId.channelId);
    formData.append('fileCode', fileCode);
    formData.append('sessionKey', sessionKey);
    // ajax請求
    const request = new XMLHttpRequest();
    request.open('POST', pictureUrl);
    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.send(formData);

    request.onreadystatechange = () => {
      if (request.readyState === 4 && request.status === 200) {
        const result = JSON.parse(request.responseText);
        if (result.success === false) {
          Toast.hide();

          Toast.fail(result.resultMsg, 1);
        } else {
          Toast.hide();
          Toast.success('上傳成功', 1);
          // 重新刷新頁面
          const data1 = {
            channelId: utils.channelId.channelId
          };
          this.props.getIdcardPhoto(data1);
        }
      }
      if (request.status !== 200) {
        Toast.fail(request.resultMsg, 1);
      }
    };
  }

5、壓縮圖片

  dataURLtoBlob(dataurl) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

 

 

全部代碼整理

import React, { Component as C } from 'react';
import connect from 'funsee/connect';
import { Button, Toast } from 'antd-mobile';
import * as actions from './action';
import * as style from './style.scss';
import * as utils from '../../../utils/util';
import * as commonAction from '../../../common/action';

class IdCard extends C {
  constructor(props) {
    super(props);
    this.state = {
      isShow: false,
      frontUrl: '' // 正面
    };
  }
  componentDidMount() {
    // 圖片上傳 獲取 微信的 APPID等
    const data1 = {
      url: 'idCard',
      channelId: utils.channelId.channelId
    };
    this.props.getLocation(data1);

    const timer = setInterval(
      () => {
        if (this.props.getLocationResult && this.props.getLocationResult.success === true) {
          clearInterval(timer);
          const {
            appId, nonceStr, signature, timestamp
          } = this.props.getLocationResult && this.props.getLocationResult.value;
          // 獲取

          if (typeof window !== 'undefined') {
            window.wx.config({
              debug: false,
              appId, // 必填,公眾號的唯一標識
              timestamp, // 必填,生成簽名的時間戳
              nonceStr, // 必填,生成簽名的隨機串
              signature, // 必填,簽名
              jsApiList: ['chooseImage', 'getLocalImgData']
            });
          }
        }
        if (this.props.getLocationResult && this.props.getLocationResult.success === false) {
          clearInterval(timer);
          Toast.fail(this.props.getLocationResult.errorMsg);
        }
      }, 100
    );
  }

  // 選擇圖片
  chooseImage(urlParam, fileCode) {
    console.log('點擊點擊');
    const that = this;
    if (typeof window !== 'undefined') {
      wx.ready(() => {
        wx.chooseImage({
          count: 1, // 默認9
          sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
          sourceType: ['album'], // 可以指定來源是相冊還是相機,默認二者都有
          success(req) {
            // localIds 返回選定照片的本地ID列表,localId可以作為img標簽的src屬性顯示圖片
            wx.getLocalImgData({
              localId: req.localIds[0].toString(),
              success(res) {
                const { localData } = res;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                  // 蘋果的直接賦值,默認生成'data:image/jpeg;base64,'的頭部拼接
                  imageBase64 = localData;
                } else {
                  // 此處是安卓中的唯一得坑!在拼接前需要對localData進行換行符的全局替換
                  // 此時一個正常的base64圖片路徑就完美生成賦值到img的src中了
                  imageBase64 = `data:image/jpeg;base64,${localData.replace(/\n/g, '')}`;
                }

                // 重新賦值圖片
                const obj = {};
                obj[urlParam] = imageBase64;
                // 賦值圖片
                that.setState(obj);
                that.handleAvatar(that.dataURLtoBlob(imageBase64), fileCode);
              }
            });
          },
          fail() {
            Toast.show({
              type: 'text',
              text: '選擇圖片失敗!'
            });
          }
        });
      });
    }
  }

  // 上傳圖片
  handleAvatar(info, fileCode) {
    console.log('上傳圖片的fileCode===', fileCode);
    const { sessionKey, pictureUrl } = this.props.getImgListData;

    Toast.loading('Loading...', 30);
    // 創建FormData
    const form = info;
    const formData = new FormData();
    // 傳遞參數
    formData.append('file', form, 'test.jpg');
    formData.append('channelId', utils.channelId.channelId);
    formData.append('fileCode', fileCode);
    formData.append('sessionKey', sessionKey);
    // ajax請求
    const request = new XMLHttpRequest();
    request.open('POST', pictureUrl);
    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.send(formData);

    request.onreadystatechange = () => {
      if (request.readyState === 4 && request.status === 200) {
        const result = JSON.parse(request.responseText);
        if (result.success === false) {
          Toast.hide();

          Toast.fail(result.resultMsg, 1);
        } else {
          Toast.hide();
          Toast.success('上傳成功', 1);
          // 重新刷新頁面
          const data1 = {
            channelId: utils.channelId.channelId
          };
          this.props.getIdcardPhoto(data1);
        }
      }
      if (request.status !== 200) {
        Toast.fail(request.resultMsg, 1);
      }
    };
  }

  dataURLtoBlob(dataurl) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  render() {
    const { getImgListData } = this.props;
    const { frontUrl } = this.state;

    const imgFrontProps = getImgListData && getImgListData.value ? getImgListData.value.filter(item => item.fileCode === 'FC15302410810000000006') : [];
    const imgFrontUrl = imgFrontProps.length !== 0 ? imgFrontProps[0].filePath : 'http://biz-oss-public.miaogoche.cn/node-miaogoche/p_miaogouche_shangchuanzheng.png';
    // 駕駛證正面-圖片
    const imgFrontUrlResult = frontUrl || imgFrontUrl;

    return (
      <div>
        <div className={style.title}>請上傳您的中國第二代居民身份證原件<br />我們將重視和保護您的隱私</div>
        <div>
          <div className={style.frontBox} onClick={() => this.chooseImage('frontUrl', 'FC15302410810000000006')} style={{ background: `url(${imgFrontUrlResult}) no-repeat center/contain` }} />
          <div className={style.font}>身份證人相面</div>
        </div>
      </div>
    );
  }
}
IdCard.pageTitle = '拍攝身份證';

export default connect(state => ({
  getImgListData: state.module.realNameAuth_idCard.getIdcardPhoto,
  getInfoDataData: state.module.realNameAuth_idCard.getInfoData,
  saveIdCard: state.module.realNameAuth_idCard.saveIdCard,
  userCertAuthStatusResult: state.common.result,
  getLocationResult: state.common.getLocationResult
}), {
  getIdcardPhoto: actions.getIdcardPhoto,
  saveIdCardData: actions.saveIdCardData,
  getInfoData: actions.getInfoData,
  userCertAuthStatus: commonAction.userCertAuthStatus,
  getLocation: commonAction.getLocation
})(IdCard);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM