zhaoxiaoqiang
2022-08-05 e47967c1f39a1b679227f8dbbec377e7698b3b3e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
<!--
 * @Date: 2019-08-30 18:04:49
 * @LastEditors: zxq
 * @LastEditTime: 2022-08-05 13:56:46
 * @Description:
 -->
<template>
  <div class="component-photo-upload">
    <div class="photo-list">
      <!--上传按钮-->
      <div class="pic-item-box-z" @click="handleUploadPicture(1)">
        <img v-if="picZ.fileUrl" :src="picZ.fileUrl" alt />
        <img v-if="!picZ.fileUrl&&cardFont" :src="cardFont" alt />
      </div>
      <!--上传按钮-->
      <div class="pic-item-box-f" @click="handleUploadPicture(2)">
        <img v-if="picF.fileUrl" :src="picF.fileUrl" alt />
        <img v-if="!picF.fileUrl&&cardBack" :src="cardBack" alt />
      </div>
    </div>
    <!-- 真正的上传按钮-->
    <div>
      <input
        style="display: none;cursor:pointer"
        type="file"
        id='androidInputFileImage'
        ref="androidInputFileImage"
        @change="handlePhotoChange($event,1)"
        accept="image/jpg, image/jpeg, image/png"
      />
      <input
        style="display: none;cursor:pointer;"
        type="file"
        id='androidInputFileCapture'
        ref="androidInputFileCapture"
        @change="handlePhotoChange($event,2)"
        accept="image/*"
        capture="camera"
      />
    </div>
    <!--选择上传图片还是拍照-->
    <van-action-sheet
      v-model="selectModel"
      :close-on-click-overlay="false"
      cancel-text="取消"
      :actions="nav"
      @select="handleMenuSelect"
    ></van-action-sheet>
    <!-- <button @click="onclick">aa</button> -->
  </div>
</template>
 
<script>
import Bus from "../../bus";
import { SET_APP_LOADING } from "@/store/mutations-types";
import { mapMutations } from "vuex";
import EXIF from "exif-js";
import { _imgCompress, _fileToBase64 } from "@/utils/index";
import Vue from "vue";
import { ActionSheet } from "vant";
Vue.use(ActionSheet);
export default {
  name: "upLoadIdCard",
  data() {
    return {
      selectModel: false, // 模态窗选择拍照还是相册
      nav: [{ name: "拍照" }, { name: "从手机相册选择" }],
      picList: [{}, {}],
      picZ: {},
      picF: {},
      zOrf: "",
      isFirst: true
    };
  },
  props: {
    cardFont: {
      type: String
    },
    cardBack: {
      type: String
    }
  },
  watch: {
    cardFont: function(newVal, oldVal) {
      if (newVal) {
        this.picList[0].fileId = this.cardFont.slice(1);
        this.picList[0].fileUrl = this.cardFont;
      }
    },
    cardBack: function(newVal, oldVal) {
      if (this.cardBack) {
        this.picList[1].fileId = this.cardBack.slice(1);
        this.picList[1].fileUrl = this.cardBack;
      }
    }
  },
  methods: {
    ...mapMutations([SET_APP_LOADING]),
    // 处理图片上传的事件(deleteIndex---删除图片的索引)
    handlePhotoChange: function(evt,type) {
      let that = this;
      let shebei = this.judgeBrand(navigator.userAgent.toLowerCase());
      that.SET_APP_LOADING(true);
      // 图片是单选还是多选
      const files = Array.prototype.slice.call(evt.target.files);
      // 图片的处理
      files.forEach(function(file, i) {
        // 图片的拍摄方向
        var orientation;
        // 格式是否支持的判断
        if (!/\/(?:jpg|jpeg|png)/i.test(file.type)) {
          that.$vux.toast.text("仅支持jpg|png图片格式", "middle");
          that.SET_APP_LOADING(false);
          return;
        }
        // 获取文件内容
        let reader = new FileReader();
        // reader.readAsArrayBuffer(file);
        reader.onload = function(e) {
            // EXIF.getData(file, function() {
            //     orientation = EXIF.getTag(this, "Orientation");
                // console.log(orientation)
                // 使用exif,处理图片的旋转问题,然后执行回调函数(orientation永远是0);
                // if(type==2&&orientation){
                //       // 拍照上传
                //       that.getImgData(e.target.result, orientation, function(data) {
                //         // 这里可以使用校正后的图片data了
                //         var img = new Image();
                //         img.src = data;
                //         // 图片加载完毕之后进行压缩,然后上传
                //         if (img.complete) {
                          
                //           callback();
                //         } else {
                //           img.onload = callback;
                //         }
                //         // 图片的路径获取成功后
                //         function callback(){
                //           // 压缩后的图片的base64字符串
                //           let data = that.compress(img);
                //           // 调取接口上传图片
                //           that.submitUploadImg(that.fileType, data);
                //         }
                //     });
                // }else{
                  var comimg = new Image();
                  comimg.src = e.target.result;
                  comimg.onload = function(eimg){
                  let num = 1;
                  if(this.width<this.height){
                      num = 8
                  }
                  that.getImgData(e.target.result, num, function(data) {
                      // 这里可以使用校正后的图片data了
                      var img = new Image();
                      img.src = data;
                      // 图片加载完毕之后进行压缩,然后上传
                      if (img.complete) {
                        callback();
                      } else {
                        img.onload = callback;
                      }
                      // 图片的路径获取成功后
                      function callback() {
                        // 压缩后的图片的base64字符串
                        console.log(img.width,img.height)
                        let data = that.compress(img);
                        // 调取接口上传图片
                        that.submitUploadImg(that.fileType, data);
                        }
                    });
                  }
                // }
            // })
        };
        reader.readAsDataURL(file);
      });
    },
    // type文件上传的路径,data图片的base64字符串(删除图片即重新上传)
    submitUploadImg: function(type, base64) {
      let that = this;
      // 防止操作的模态窗
      let submitInfo = {
        base64Data: base64.split(",")[1], // 文件base64
        suffix: base64.split(",")[0].split(";")["0"].split("/")[1]
      };
      this.$api.uploadFile(submitInfo).then(
        res => {
          if (that.zOrf == 1) {
            that.picZ = {
              fileUrl: res.body.fileUrl,
              fileId: res.body.fileId
            };
            that.picList[0] = that.picZ;
          } else {
            that.picF = {
              fileUrl: res.body.fileUrl,
              fileId: res.body.fileId
            };
            that.picList[1] = that.picF;
          }
          if (this.picList[1].fileId && this.picList[0].fileId) {
            this.getIdCardInfo();
          }
          that.SET_APP_LOADING(false);
        },
        error => {
          this.SET_APP_LOADING(false);
        }
      );
    },
    // 获取身份证信息
    getIdCardInfo() {
      if (!this.isFirst) {
        this.$api
          .getIdCardInfo({
            idBackId: this.picList[1].fileId,
            idFrontId: this.picList[0].fileId
          })
          .then(res => {
            let obj = res.body;
            obj.idBackUrl = this.picList[1].fileUrl;
            obj.idFrontUrl = this.picList[0].fileUrl;
            Bus.$emit("getIdUserInfo", obj);
          });
      }
    },
    // 图片旋转处理
    getImgData: function(img, dir, next) {
      // @param {string} img 图片的base64
      // @param {int} dir exif获取的方向信息
      // @param {function} next 回调方法,返回校正方向后的base64
      var image = new Image();
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      image.onload = function() {
        let resultWidth = 0;
        let resultHeight = 0;
        let maxWidthOrHeight = 1024;
        let drawWidth = this.naturalWidth;
        let drawHeight = this.naturalHeight;
        // 以下改变图片大小,控制最大宽度为1024
        var maxSide = Math.max(drawWidth, drawHeight);
        if (maxSide > maxWidthOrHeight) {
          let minSide = Math.min(drawWidth, drawHeight);
          minSide = (minSide / maxSide) * maxWidthOrHeight;
          maxSide = maxWidthOrHeight;
          if (drawWidth > drawHeight) {
            resultWidth = maxSide;
            resultHeight = minSide;
          } else {
            resultWidth = minSide;
            resultHeight = maxSide;
          }
        } else {
          resultWidth = drawWidth;
          resultHeight = drawHeight;
        }
        if (dir === 3) {
          canvas.width = resultWidth;
          canvas.height = resultHeight;
          ctx.translate(resultWidth, resultHeight);
          ctx.rotate(Math.PI);
        } else if (dir === 6) {
          canvas.width = resultHeight;
          canvas.height = resultWidth;
          ctx.translate(resultHeight, 0);
          ctx.rotate(Math.PI / 2);
        } else if (dir === 8) {
          canvas.width = resultHeight;
          canvas.height = resultWidth;
          ctx.translate(0, resultWidth);
          ctx.rotate(-Math.PI / 2);
        } else {
          canvas.width = resultWidth;
          canvas.height = resultHeight;
        }
        ctx.drawImage(this, 0, 0, resultWidth, resultHeight);
        // 返回校正图片
        next(canvas.toDataURL("image/jpeg", 0.8));
      };
      image.src = img;
    },
    compress(img) {
        let quality = 0.92, //压缩比例
        w = img.width,
        h = img.height,
        canvas = document.createElement("canvas"),
        ctx = canvas.getContext("2d");
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(img, 0, 0, w, h);
        return canvas.toDataURL("image/jpeg", quality);
    },
    checkAuth(id) {
      // authStatus: 0 未授权  1授权---用户授权后才能执行下一步
      this.$api
        .checkAuth({
          fileId: id
        })
        .then(res => {
          if (res.body.authStatus === 1) {
            this.$emit("on-check-auth", "下一步");
          }
        });
    },
    // 点击上传按钮
    handleUploadPicture(i) {
      this.isFirst = false;
      this.zOrf = i;
      // this.$refs.androidInputFileCapture.click();
      this.selectModel = true;
    },
    // 选择拍照或者相册选项
    handleMenuSelect(item, index) {
      console.log( this.$refs.androidInputFileCapture )
      if (index === 0) {
        this.$refs.androidInputFileCapture.click();
      } else {
        this.$refs.androidInputFileImage.click();
      }
      this.selectModel = false;
    },
    // 处理图片的删除
    handleDeletePicture(index) {
      this.selectModel = true;
    },
    judgeBrand(sUserAgent) {
       var isIphone = sUserAgent.match(/iphone/i) == "iphone";
       var isHuawei = sUserAgent.match(/huawei/i) == "huawei";
       var isHonor = sUserAgent.match(/honor/i) == "honor";
       var isOppo = sUserAgent.match(/oppo/i) == "oppo";
       var isOppoR15 = sUserAgent.match(/pacm00/i) == "pacm00";
       var isVivo = sUserAgent.match(/vivo/i) == "vivo";
       var isXiaomi = sUserAgent.match(/mi\s/i) == "mi ";
       var isXiaomi2s = sUserAgent.match(/mix\s/i) == "mix ";
       var isRedmi = sUserAgent.match(/redmi/i) == "redmi";
       var isSamsung = sUserAgent.match(/sm-/i) == "sm-";
       if (isIphone) {
           return 'iphone';
       } else if (isHuawei || isHonor) {
           return 'huawei';
       } else if (isOppo || isOppoR15) {
           return 'oppo';
       } else if (isVivo) {
           return 'vivo';
       } else if (isXiaomi || isRedmi || isXiaomi2s) {
           return 'xiaomi';
       } else if (isSamsung) {
           return 'samsung';
       } else {
           return 'default';
       }
   }
  },
  created(){
  //  let 
  //  console.log(shebei);
  }
};
</script>
 
<style lang="less" scoped >
.component-photo-upload {
  .pic-title {
    h4 {
      padding: 10px 0;
      font-size: 15px;
      line-height: 1;
      color: #333;
      font-weight: normal;
    }
  }
 
  .photo-list {
    // .pic-item-box{
    //     width: 239px;
    //     height: 134px;
    // }
 
    .pic-item-box-z {
      width: 239px;
      height: 134px;
      background-image: url("../../../static/img/idcardz.png");
      background-size: cover;
      margin: auto;
      margin-bottom: 20px;
 
      img {
        width: 100%;
        height: 100%;
      }
    }
 
    .pic-item-box-f {
      width: 239px;
      height: 134px;
      background-image: url("../../../static/img/idcardf.png");
      background-size: cover;
      margin: auto;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>