uniapp上传图片兼容H5和小程序获取微信图像

原由:h5中没有微信图像获取,小程序中图方便可以使用微信图像上传

1.在uniapp页面中 info.vue中

   <!-- #ifdef H5 -->
    <!-- 在h5中执行标签内代码 -->
	<button class="avatar-wrapper" open-type="chooseAvatar" @click="upPic">
		<image class="avatar" :src="avatar"></image>
	</button>
    <!-- #endif -->

	<!-- #ifdef MP -->
	<!-- 在小程序中执行标签内代码 -->
	<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
		<image class="avatar" :src="avatar"></image>
	</button>
	<!-- #endif -->

2.在js中使用对应的上传方法

    /* 获取微信图像 */
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				console.log('微信图像', avatarUrl);
				uni.uploadFile({
					url: '图片上传接口', //仅为示例,非真实的接口地址
					filePath: avatarUrl,
					name: 'file',
					header: {
						token: uni.getStorageSync('userInfo').token
					},
					success: (res) => {
						// console.log('上传成功后返回', res);						
					}
				})
			},
    // uni普通上传
			upPic() {
				uni.chooseImage({
					count: 1, //默认9,这里设置只允许选择一张图片
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: ['album'], //这里选择从相册选择,也可删除此项设置默认拍照和相册两种选择
					success: res => {
						// 实际开发中,成功的回调函数中是一个上传图片到服务器的接口,这里只是做了简单的效果,实际根据接口需要的参数格式进行上传
						// console.log(JSON.stringify(res.tempFilePaths)); 打印的结果是以数组方式返回的,所以我们只需要取第一个值:["blob:http://localhost:8080/c18cded6-ab83-4d0e-9ccd-ce2e402b7d3f"] 
						let avatarUrl = res.tempFilePaths[0] // 将选择的图片赋值给我们定义的cover
						uni.uploadFile({
							url: '图片上传接口', //仅为示例,非真实的接口地址
							filePath: avatarUrl,
							name: 'file',
							header: {
								token: uni.getStorageSync('userInfo').token
							},
							success: (res) => {
								console.log('上传成功后返回', res);
							}
						})
					}
				});
			},

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值