需求背景:在app项目中需要嵌入h5项目的页面,并且该h5页面需要上传图片的功能。
前期方案:上传组件使用h5的input的方案,但是当我完成,真机操作后,发现坑来了,安卓机无法选择拍照上传图片,并且与原生api的样式不一致,因此使用另一种方案,故有此h5调用app原生上传图片。
安装dsbridge
npm i dsbridge
webBridge模块
app原生开发也需要写上相对应的方法,h5才能使用,如调上传图片api —— startPhotoForResult,原生也需命名一致!
// webBridge.js
/**
* webBridge模块
*/
var dsBridge = require('dsbridge')
var u = navigator.userAgent
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
var that = {}
/**
* 调用app方法
* @param {string} 方法名称
* @param {Function} 回调函数
* @param {object} 附加数据
*/
that.startPhotoForResult = type => {
return new Promise(resolve => {
if (dsBridge.hasNativeMethod('startPhotoForResult', 'all')) {
dsBridge.call('startPhotoForResult', type, res => {
let data = res
if (typeof res === 'string') {
data = JSON.parse(data)
}
resolve(data)
})
} else { // 兼容H5操作
const Tobase64 = fileObj => {
const reader = new FileReader()
reader.readAsDataURL(fileObj)
reader.onload = function(e) {
const base64 = e.target.result.split(';base64,')[1]
resolve({ image: base64 })
}
}
let input = document.createElement('INPUT')
input.type = 'file'
input.addEventListener('change', e => {
Tobase64(e.target.files[0])
})
input.click()
input = null
}
})
}
window.webBridge = that
export default window.webBridge
引入main.js
// main.js
import webBridge from '@/lib/webBridge'
使用
// html
<div @click="startPhotoForResult({type:1})"></div>
// js
// 点击调用上传
startPhotoForResult({ type }) {
// 调用原生事件
webBridge.startPhotoForResult(type)
.then(data => {
// 返回形式根据原生而定
const img = `data:image/png;base64,${data.image}`
// this.uploadAjax(img) 调用后端接口
})
},
最后效果如下:
有什么问题,可留言沟通交流~~