HTML5拍照上传图片与调用微信接口扫二维码
html
<span class="iconfont scan" @click="scan"> <input ref="camera" type="file" @change="toBase64" style="position: absolute;top:50rem" accept="image/*" capture="camera" /> 拍照
</span>
js
scan() { this.$refs.camera.click(); console.log('开启拍照功能'); },
toBase64(event) { let file = event.target.files[0]; if (!/image\/\w+/.test(file.type)) { alert('请确保文件为图像类型'); return; } let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(event) { compress(event.target.result); }; let compress = function(res) { let img = new Image(); let maxH = 160; img.onload = function() { let cvs = document.createElement('canvas'); let ctx = cvs.getContext('2d'); if (img.height > maxH) { img.width *= maxH / img.height; img.height = maxH; } cvs.width = img.width; cvs.height = img.height; ctx.clearRect(0, 0, cvs.width, cvs.height); ctx.drawImage(img, 0, 0, img.width, img.height); let dataUrl = cvs.toDataURL('image/jpeg', 0.6); // 上传 console.log(dataUrl); }; img.src = res; }; },
微信JSAPI部分
scan() { // this.$refs.camera.click(); const apiList = ['scanQRCode', 'chooseImage', 'uploadImage']; this.configWx(apiList, () => { // eslint-disable-next-line no-undef wx.ready(function() { // eslint-disable-next-line no-undef // wx.scanQRCode({ // needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, // scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有 // success: function(res) { // let result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果 // console.log(result); // }, // fail: function() { // if (typeof fail === 'function') { // console.log('调用扫码失败'); // } // } // }); // eslint-disable-next-line no-undef wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 指定是原图还是压缩图,默认都有 sourceType: ['album', 'camera'], // 指定来源是相册还是相机,默认都有 success: function(res) { let localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 // eslint-disable-next-line no-undef wx.uploadImage({ localId: localIds.toString(), // 需要上传的图片的ID,由chooseImage接口获得 isShowProgressTips: 1, // 进度提示 success: function(res) { let mediaId = res.serverId; // 返回图片的服务器端ID,即mediaId //将获取到的 mediaId 传入后台 方法savePicture uploadImageFile(mediaId).then(res => { console.log(res.data.data); }); }, fail: function(res) { this.$toast('图片上传失败,请重试'); } }); } }); }); }); },
configWx(apiList, callback) { let url = location.href.split('#')[0]; let that = this; getWXSign(url).then(res => { console.log(res.data.data); that.appId = res.data.data.appid; that.timestamp = res.data.data.timestamp; that.nonceStr = res.data.data.noncestr; that.signature = res.data.data.signature; // eslint-disable-next-line no-undef wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来, appId: that.appId, // 必填,公众号的唯一标识 timestamp: that.timestamp, // 必填,生成签名的时间戳 nonceStr: that.nonceStr, // 必填,生成签名的随机串 signature: that.signature, // 必填,签名 jsApiList: apiList // 必填,需要使用的JS接口列表 }); setTimeout(() => { callback(); }, 500); }); },