记录一次h5上传身份证照片、上传人面像

本文详细描述了如何在移动端应用中上传身份证照片,包括真人像面、国徽面和自拍人像的要求,并介绍了上传过程中的验证步骤。通过`addIdPositive`、`addIdBack`和`addHead`方法处理身份证正面、背面和头像的识别,最后完成登录身份信息的过程。
摘要由CSDN通过智能技术生成
<template>
  <div class="pageOuter">
    <div class="Submit">
      <div class="formModel">
        <div class="item">
          <div class="label">真实姓名</div>
          <div class="inptItem">
            <input
              type="tel"
              placeholder="请上传您的身份证"
              v-model="currentInfo.realname || ''"
              disabled
            />
          </div>
        </div>
        <div class="item">
          <div class="label">身份证号码</div>
          <div class="inptItem">
            <input
              type="text"
              placeholder="请上传您的身份证"
              v-model="currentInfo.idcard || ''"
              disabled
            />
          </div>
        </div>
      </div>

      <div class="submitModel">
        <div class="title">上传身份证</div>
        <div class="box">
          <div class="item">
            <div class="img icon1">
              <div class="imgBox" v-if="firstImage">
                <img :src="firstImage" alt="" />
              </div>

              <template>
                <input
                  type="file"
                  id="firstImage"
                  ref="firstImage"
                  accept="image/*"
                  capture="camera"
                  @change="upload($event, 'firstImage')"
                  v-if="isAndroid"
                />
                <input
                  type="file"
                  id="upload"
                  ref="uploadInput"
                  accept="image/*"
                  capture="camera"
                  @change="upload($event, 'firstImage')"
                  v-else
                />
              </template>
            </div>
            <div class="txt">身份证人像面</div>
          </div>
          <div class="item">
            <div class="img icon2">
              <div class="imgBox" v-if="secondImage">
                <img :src="secondImage" alt="" />
              </div>

              <template>
                <input
                  type="file"
                  id="secondImage"
                  ref="secondImage"
                  accept="image/*"
                  capture="camera"
                  @change="upload($event, 'secondImage')"
                  v-if="isAndroid"
                />
                <input
                  type="file"
                  id="upload"
                  ref="uploadInput"
                  accept="image/*"
                  capture="camera"
                  @change="upload($event, 'secondImage')"
                  v-else
                />
              </template>
            </div>
            <div class="txt">身份证国徽面</div>
          </div>
        </div>
        <div class="title">上传人像</div>
        <div class="item">
          <div class="img icon3">
            <div class="imgBox" v-if="thirdImage">
              <img :src="thirdImage" alt="" />
            </div>
            <template>
              <input
                type="file"
                id="thirdImage"
                ref="thirdImage"
                accept="image/*"
                capture="user"
                @change="upload($event, 'thirdImage')"
                v-if="isAndroid"
              />
              <input
                type="file"
                id="upload"
                ref="uploadInput"
                accept="image/*"
                capture="user"
                @change="upload($event, 'thirdImage')"
                v-else
              />
            </template>
          </div>
          <div class="txt">自拍人像</div>
        </div>
        <div class="title">上传要求</div>
        <div class="rule">
          <div class="txt">一、身份证照片完整,无缺失,无遷挡</div>
          <div class="txt">二、身份证照片清晰,内容不模糊</div>
          <div class="txt">三、身份证照片无反光,影响识别</div>
          <div class="txt">
            四、人像照片能看清完整的人物胸腔以上,脸部无遮挡
          </div>
        </div>
      </div>

      <div class="submitBtn isTouch" data-touch="true" @click="goLogin">
        提交
      </div>
    </div>
  </div>
</template>

<script>
import { addIdPositive, addIdBack, addHead, goLogin } from "network/api.js";
export default {
  name: "Submit",
  data() {
    return {
      isAndroid: true,
      picValue: "",
      headerImage: "",
      firstImage: "",
      secondImage: "",
      thirdImage: "",
      // 个人信息
      currentInfo: "",
      // 人面像验证标识
      positive_key: "",
      // 身份证国徽面验证标识
      back_key: "",
      // 自拍人像验证标识
      head_key: "",
    };
  },
  created() {
    console.log(this.$route);
    console.log(this.$store.state.JHParams);
    this.getEnvFunc();
  },
  methods: {
    // 获取设备环境
    getEnvFunc() {
      let env = this.$common.judgeEquipment();
      console.log(env);
      if (env === "isAndroid") return (this.isAndroid = true);
      else if (env === "isIos") return (this.isAndroid = false);
    },
    handleInput(e, current) {
      console.log("input", e);
      console.log("input", current);
    },
    upload(e, current) {
      // 验证
      if (
        current === "thirdImage" &&
        (!this.currentInfo.realname || !this.currentInfo.realname)
      )
        return this.$toast("请先上传身份证人像面");
      console.log("1", e);
      console.log("2", current);
      let files = e.target.files || e.dataTransfer.files;
      console.log();
      if (!files.length) return;
      this.picValue = files[0];
      this.imgPreview(this.picValue, current);
      console.log(this.picValue);
    },
    imgPreview(file, current) {
      let self = this;
      let Orientation;
      if (current !== "thirdImage") {
        // 去获取拍照时的信息,解决拍出来的照片旋转问题
        EXIF.getData(file, function () {
          Orientation = EXIF.getTag(this, "Orientation");
          console.log("信息", Orientation);
        });
      }
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function () {
          let result = this.result;
          let img = new Image();
          img.src = result;
          // 统一压缩再上传,统一上传图片格式
          img.onload = function () {
            let data = self.compress(img, Orientation);
            self[current] = data;
            // 发起请求
            if (current === "firstImage") {
              self.addIdPositive(self[current]);
            } else if (current === "secondImage") {
              self.addIdBack(self[current]);
            } else if (current === "thirdImage") {
              self.addHead(self[current]);
            }
          };

          //  判断图片是否大于100K,是就直接上传,反之压缩图片
          // if (this.result.length <= 100 * 1024) {
          //   self[current] = this.result;
          //   // 发起请求
          //   if (current === "firstImage") {
          //     self.addIdPositive(self[current]);
          //   } else if (current === "secondImage") {
          //     self.addIdBack(self[current]);
          //   } else if (current === "thirdImage") {
          //     self.addHead(self[current]);
          //   }
          // } else {
          //   img.onload = function () {
          //     let data = self.compress(img, Orientation);
          //     self[current] = data;
          //     // 发起请求
          //     if (current === "firstImage") {
          //       self.addIdPositive(self[current]);
          //     } else if (current === "secondImage") {
          //       self.addIdBack(self[current]);
          //     } else if (current === "thirdImage") {
          //       self.addHead(self[current]);
          //     }
          //   };
          // }

          // console.log("图片", self.headerImage);
        };
      }
    },
    compress(img, Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      // 瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      // 如果图片大于四百万像素,计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width = width / ratio;
        height = height / ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //        铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      // 如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      // 修复ios上传图片的时候 被旋转的问题
      if (Orientation !== "" && Orientation !== 1) {
        switch (Orientation) {
          case 6: // 需要顺时针(向左)90度旋转
            this.rotateImg(img, "left", canvas);
            break;
          case 8: // 需要逆时针(向右)90度旋转
            this.rotateImg(img, "right", canvas);
            break;
          case 3: // 需要180度旋转
            this.rotateImg(img, "right", canvas); // 转两次
            this.rotateImg(img, "right", canvas);
            break;
        }
      }
      // 进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      console.log("压缩前:" + initSize);
      console.log("压缩后:" + ndata.length);
      console.log(
        "压缩率:" + ~~((100 * (initSize - ndata.length)) / initSize) + "%"
      );
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    rotateImg(img, direction, canvas) {
      // 最小与最大旋转方向,图片旋转4次后回到原方向
      const minStep = 0;
      const maxStep = 3;
      if (img == null) return;
      // img的高度和宽度不能在img元素隐藏后获取,否则会出错
      let height = img.height;
      let width = img.width;
      let step = 2;
      if (step == null) {
        step = minStep;
      }
      if (direction === "right") {
        step++;
        // 旋转到原位置,即超过最大值
        step > maxStep && (step = minStep);
      } else {
        step--;
        step < minStep && (step = maxStep);
      }
      // 旋转角度以弧度值为参数
      let degree = (step * 90 * Math.PI) / 180;
      let ctx = canvas.getContext("2d");
      switch (step) {
        case 0:
          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0);
          break;
        case 1:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, 0, -height);
          break;
        case 2:
          canvas.width = width;
          canvas.height = height;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, -height);
          break;
        case 3:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, 0);
          break;
      }
    },
    // 身份证人像面
    async addIdPositive(pic) {
      // 发起请求
      let params = {
        pic,
        type: 1,
        mobile: this.$route.query.mobile,
      };
      console.log("参数", params);
      params = this.$public170.webEncrypt(JSON.stringify(params));
      let { data } = await addIdPositive({ params });
      if (data.code !== 1000) {
        // 上传失败清除图片
        this.firstImage = "";
        this.currentInfo = "";
        console.log("失败1");
        let firstImageObj = document.getElementById("firstImage");
        firstImageObj.value = "";
        return this.$toast.fail(data.msg);
      }
      let ost = JSON.parse(this.$public170.webDecrypt(data.data));
      console.log("身份证人像面返回", ost);
      this.positive_key = ost.positive_key;
      this.currentInfo = ost;

      // 重新上传去除其他的
      this.secondImage = "";
      let secondImageObj = document.getElementById("secondImage");
      secondImageObj.value = "";

      this.thirdImage = "";
      let thirdImageObj = document.getElementById("thirdImage");
      thirdImageObj.value = "";
    },
    // 身份证国徽面
    async addIdBack(pic) {
      // 发起请求
      let params = {
        pic,
        type: 2,
        mobile: this.$route.query.mobile,
      };
      console.log("参数", params);
      params = this.$public170.webEncrypt(JSON.stringify(params));
      let { data } = await addIdBack({ params });
      if (data.code !== 1000) {
        // 上传失败清除图片
        this.secondImage = "";
        console.log("失败2");
        let secondImageObj = document.getElementById("secondImage");
        secondImageObj.value = "";
        return this.$toast.fail(data.msg);
      }
      let ost = JSON.parse(this.$public170.webDecrypt(data.data));
      console.log("身份证国徽面返回", ost);
      this.back_key = ost.back_key;
    },
    // 自拍人像
    async addHead(pic) {
      // 自拍人像去除 'data:image/jpeg;base64,' 字符
      let photo = pic.replace("data:image/jpeg;base64,", "");
      // 发起请求
      let params = {
        photo,
        realname: this.currentInfo.realname,
        idcard: this.currentInfo.idcard,
        mobile: this.$route.query.mobile,
      };
      console.log("参数", params);
      params = this.$public170.webEncrypt(JSON.stringify(params));
      let { data } = await addHead({ params });
      if (data.code !== 1000) {
        // 上传失败清除图片
        this.thirdImage = "";
        console.log("失败3");
        let thirdImageObj = document.getElementById("thirdImage");
        thirdImageObj.value = "";
        return this.$toast.fail(data.msg);
      }
      let ost = JSON.parse(this.$public170.webDecrypt(data.data));
      console.log("自拍人像返回", ost);
      this.head_key = ost.head_key;
    },
    // 提交身份信息登录
    async goLogin(pic) {
      // 发起请求
      let params = {
        user_name: this.currentInfo.realname,
        idcard: this.currentInfo.idcard,
        store_id: this.$store.state.storeId,
        c_user_id: this.$store.state.JHParams.user_id,
        c_sign: this.$store.state.JHParams.ccbSign,
        c_timestamp: this.$store.state.JHParams.ccbTime,
        mobile: this.$route.query.mobile,
        head_key: this.head_key,
        back_key: this.back_key,
        positive_key: this.positive_key,
      };
      console.log("参数", params);
      params = this.$public170.webEncrypt(JSON.stringify(params));
      let { data } = await goLogin({ params });
      if (data.code !== 1000) return this.$toast.fail(data.msg);
      let ost = JSON.parse(this.$public170.webDecrypt(data.data));
      console.log("提交身份信息登录返回", ost);
      this.$store.commit("SET_TOKEN", ost.token);
      this.$toast.success(data.msg);
      setTimeout(() => {
        this.$router.replace({ name: "Home" });
      }, 2000);
    },
  },
};
</script>

<style lang="less" scoped>
.Submit {
  width: 100%;
  min-height: 14.34rem;
  height: 100%;
  background: #f6f3ee
    url(https://vncdn.mobi88.cn/gzjh_moutai/ct1008/images/bg.png) no-repeat;
  background-size: contain;
  box-sizing: border-box;
  padding-top: 0.3rem;
  padding-bottom: 0.3rem;
  .formModel {
    width: 6.8rem;
    height: 2.31rem;
    background: #ffffff;
    box-shadow: 0 0 0.2rem 0 rgba(199, 195, 187, 0.56);
    border-radius: 0.2rem;
    margin: 0 auto 0.2rem;
    box-sizing: border-box;
    padding-top: 0.19rem;
    .item {
      width: 6rem;
      height: 0.96rem;
      display: flex;
      align-items: center;
      margin: auto;
      .label {
        width: 1.5rem;
        height: 100%;
        color: #666666;
        font-size: 0.28rem;
        line-height: 0.96rem;
        font-weight: bold;
      }

      .inptItem {
        width: 4.4rem;
        margin-left: 0.1rem;
        height: 100%;
        position: relative;
        &::before {
          content: "";
          box-sizing: border-box;
          pointer-events: none;
          border-bottom: 0.02rem solid #eee;
          -webkit-transform: scale(0.5);
          position: absolute;
          top: -50%;
          left: -50%;
          right: -50%;
          bottom: -50%;
        }
        input {
          width: 100%;
          height: 100%;
          &::placeholder {
            font-size: 0.28rem;
            font-weight: normal;
            color: #999999;
            line-height: 0.96rem;
          }
          &:disabled {
            background: transparent;
          }
        }
      }
    }
  }

  .submitModel {
    width: 6.8rem;
    height: 9.62rem;
    background: #ffffff;
    box-shadow: 0 0 0.2rem 0 rgba(199, 195, 187, 0.56);
    border-radius: 0.2rem;
    box-sizing: border-box;
    padding: 0.3rem 0.48rem;
    margin: auto;
    .title {
      font-size: 0.28rem;
      font-weight: bold;
      color: #333333;
      line-height: 0.6rem;
    }
    .box {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .item {
      margin-bottom: 0.3rem;
      display: flex;
      flex-direction: column;
      align-items: center;
      .img {
        width: 2.69rem;
        height: 1.85rem;
        position: relative;
        .imgBox {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #fff;
          img {
            max-width: 100%;
            max-height: 100%;
          }
        }

        input {
          position: absolute;
          right: 0;
          top: 0;
          left: 0;
          bottom: 0;
          z-index: 2;
          opacity: 0;
          width: 100%;
          height: 100%;
        }
        &.icon1 {
          background: url(https://vncdn.mobi88.cn/gzjh_moutai/ct1008/images/submitIcon1.png)
            no-repeat;
          background-size: contain;
        }
        &.icon2 {
          background: url(https://vncdn.mobi88.cn/gzjh_moutai/ct1008/images/submitIcon2.png)
            no-repeat;
          background-size: contain;
        }
        &.icon3 {
          background: url(https://vncdn.mobi88.cn/gzjh_moutai/ct1008/images/submitIcon3.png)
            no-repeat;
          background-size: contain;
        }
      }
      .txt {
        text-align: center;
        font-size: 0.24rem;
        font-weight: normal;
        color: #666666;
        line-height: 0.5rem;
      }
    }
    .rule {
      width: 6.01rem;
      height: 1.86rem;
      background: #f5f5f5;
      border-radius: 0.1rem;
      margin: auto;
      box-sizing: border-box;
      padding: 0.14rem 0.2rem;
      .txt {
        font-size: 0.22rem;
        font-weight: normal;
        color: #999999;
        line-height: 0.4rem;
      }
    }
  }

  .submitBtn {
    width: 6.22rem;
    height: 0.84rem;
    text-align: center;
    background: url(https://vncdn.mobi88.cn/gzjh_moutai/ct1008/images/nextBtn.png)
      no-repeat;
    background-size: contain;
    text-align: center;
    font-size: 0.3rem;
    font-weight: bold;
    color: #ffffff;
    line-height: 0.84rem;
    margin: 0.4rem auto 0;
  }
}
</style>

修复input传一次文件后无法再次触发change事件。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值