1、引入的方式有两种,可用npm也可直接下载js文件引入
npm install jweixin-module --save
2、依赖下载了之后可直接在需要掉起图片上传功能的页面引入并直接配置参数:
var wx = require('jweixin-module');
3、封装一个共用的注入权限的方法并在onShow里面调用此方法
// 共用方法
gongyong() {
// 记录进入app时的url
if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
window.entryUrl = location.href.split('#')[0]
}
let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
// 进行签名的时候 Android 不用使用之前的链接, ios 需要
let signLink = isiOS ? window.entryUrl : location.href.split('#')[0];
// console.warn('-----------当前签名url--------------')
console.log(signLink, '签名url',window.location.href.split('#')[0],location.href.split('#')[0])
// var uri = encodeURIComponent(location.href.split('#')[0]); //获取当前url然后传递给后台获取授权和签名信息
var uri = encodeURIComponent(signLink); //获取当前url然后传递给后台获取授权和签名信息
//服务端进行签名
uni.request({
url: '你自己的接口地址', //你的接口地址
data: {
url: uri
},
success: (resss) => {
console.log('------签名返回数据------')
console.log(resss.data)
//返回需要的参数appId,timestamp,noncestr,signature等
//注入config权限配置
wx.config({
debug: false,
appId: resss.data.appId,
timestamp: resss.data.timestamp,
nonceStr: resss.data.nonceStr,
signature: resss.data.signature,
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'editAddress', 'chooseImage',
'onMenuShareAppMessage', 'onMenuShareTimeline', 'previewImage', 'uploadImage',
'downloadImage', 'chooseWXPay', 'getLocation'
]
});
wx.ready(function() {
console.log('config注入成功')
})
wx.error(function(res){
console.log(res, 'config信息验证失败会执行 error 函数')
// config信息验证失败会执行 error 函数,如签名过期导致验证失败,具体错误信息可以打开 config 的debug模式查看,也可以在返回的 res 参数中查看,对于 SPA 可以在这里更新签名。
});
}
})
},
4、在点击操作的时候调起图片上传接口(id是因为我的页面有多个图片上传,所以id是用来区分的。)
// 上传图片
clickuploadimg(id) {
let that = this
let imgnum = 0
if(id == 4 || id == 5 || id == 6) {
imgnum = 1
} else {
imgnum = 9
}
let num = 0
wx.chooseImage({
count: imgnum, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
const tempFilePaths = res.localIds; // res.localIds是一个数组,返回选定照片的本地 ID 列表,localId可以作为 img 标签的 src 属性显示图片
if(id == 1) {
// 个人照片
that.xianzhiphoto = that.xianzhiphoto.concat(res.localIds)
} else if(id == 2) {
} else if(id == 3) {
} else if (id == 4) {
} else if (id == 5) {
} else if (id == 6) {
}
uni.showLoading({
title: '上传中~',
});
for(var i = 0; i < tempFilePaths.length; i++){
wx.uploadImage({
localId: tempFilePaths[i], // 需要上传的图片的本地ID,由 chooseImage 接口获得
isShowProgressTips: tempFilePaths.length, // 默认为1,显示进度提示
success: function (respo) { // respo.serverId为字符串(就是后端需要的media_id)
num = num + 1
if(id == 1) {
// 个人照片
that.xianzhiphotoid.push(respo.serverId)
} else if(id == 2) {
} else if(id == 3) {
} else if(id == 4) {
} else if(id == 5) {
} else if(id == 6) {
}
if (num == tempFilePaths.length) {
uni.hideLoading()
uni.showToast({
title: "上传成功",
icon: 'success',
})
// that.show = true
}
}
});
}
},
fail: function(res) {
uni.showToast({
title: "上传成功",
icon: res,
})
},
})
},
效果展示