H5 input 拍照
页面开始显示一个拍照图片,点击拍照之后,返回图片并替换拍照图片
一、页面
二、代码
1.HTML
<template>
<div id="identityCheck" style="background-color: #f7f7f7;font-size: 12px;">
<div style="width: 100%;text-align: center;height: 113px;margin-top: 40px">
<div ref="face" class="identityImage face" @click="takePhotoFace"></div>
<div style="width: 20px;display: inline-block;"></div>
<div ref="back" class="identityImage back" @click="takePhotoBack"></div>
</div>
</div>
<input style="display: none;" ref="faceInput" type="file" accept="image/*" capture="camera" @change="backImag" />
<input style="display: none;" ref="backInput" type="file" accept="image/*" capture="camera" @change="backImag2" />
</div>
</template>
2.js
<script>
import { Vue, Component } from "vue-property-decorator";
import { NativeUI } from "../../utils/NativeUI";
@Component({
name: "IndentityCheck"
})
export default class IndentityCheck extends Vue {
//拍身份证证明照
takePhotoFace() {
this.$refs.faceInput.click();
}
//拍身份证背面照
takePhotoBack() {
this.$refs.backInput.click();
}
backImag(e) {
const file = e.target.files[0];
console.log(file.size / 1024);
const fileName = this.getObjectURL(file);
this.$refs.face.style.backgroundImage = `url(${fileName})`;
NativeUI.showWaiting("正在上传证件照图片,请稍后. . .");
const that = this;
this.fileToBase64(file)
.then(function(result) {
//打印base64的值
console.log(result);
NativeUI.closeWaiting();
})
.catch(function(error) {
console.log(error);
NativeUI.closeWaiting();
});
}
backImag2(e) {
const file = e.target.files[0];
console.log(file.size / 1024);
const fileName = this.getObjectURL(file);
this.$refs.back.style.backgroundImage = `url(${fileName})`;
NativeUI.showWaiting("正在上传证件照图片,请稍后. . .");
const that = this;
this.fileToBase64(file)
.then(function(result) {
console.log(result);
NativeUI.closeWaiting();
})
.catch(function(error) {
console.log(error);
NativeUI.closeWaiting();
});
}
// 文件转 base64
fileToBase64(file) {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(ev) {
resolve(ev.target.result);
};
});
}
//获取文件路径
getObjectURL(file) {
let url = null;
if (window.createObjectURL != undefined) {
// basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) {
// mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {
// webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
}
使用两个不展示的 input标签,当图片点击的时候,分别触发各自的input标签,使用input标签拍照。在 input 的 change事件里面拿到返回的文件,读取文件地址 并把文件转化为 base64 。