概述
uni-app 微信小程序原生上传图片功能封装,具体使用根据个人情况而定。
组件自定义属性与方法描述
- isShow:布尔值,默认为true true:不显示上传图标 false:显示上传图标
- count:Number类型,上传图片张数,总计默认最多9张
- showUrl: Array类型,组件绑定值(后台返回已上传图片数据)
- uploadUrl: String类型,上传图片的后台接口
- bindmyevent:function类型,自定义事件
适用场景
- uni-app原生组件
- 微信小程序授权校验之后,进行拍照
- 可以统计本次上传图片的失败次数
- 样式根据自己需要自行调整
- 图片可删除
- 图片可预览
使用方式介绍
vue(html)
// html
<UploadImage :isShow="false" style="flex:1" bindmyevent="myEventListener" :count='countPic' :showUrl="sugonForm.picUrl" :uploadUrl="uploadImgUrl"></UploadImage>
必要封装js文件引入
// 拍照组件
import UploadImage from '@/components/UploadImage.vue'
export default{
mixins:[userPermission],
data(){
return{
authorScope:'scope.camera', // 权限
countPic:9, // 图片个数
uploadImgUrl:'/wechatApp/fireEye/imageUpload' // 上传图片后台接口
}
},
methods:{
//监听组件事件,返回的结果
myEventListener(e) { // 内部代码根据情况而定
console.log(e)
},
}
}
组件封装
组件内使用的import userPermission from '@/mixins/userPermission.js’具体封装,需要参考权限授权封装地址
<!-- uni-app自带组件版本 -->
<template>
<view class="upload-image">
<view class="image-list" v-if="detailPics.length>0">
<block v-for="(item,index) in detailPics" :key="index">
<view class="pic">
<text :data-index="index" class="delete_btn" v-if="isShow" @click="deletePic"></text>
<image @click="previewImage" class="img-item" :src="baseUrl+item" bindlongpress="bindlongpressimg"
:data-id='index'></image>
</view>
</block>
</view>
<view class="chooseimg" v-if="!isShow" @click="judgeAuthorize(authorScope,'摄像机',getTakePhoto)">
<view class="weui-uploader__input-box"></view>
</view>
</view>
</template>
<script>
// 权限判断
import userPermission from '@/mixins/userPermission.js'
import ipConfig from '@/utils/ipConfig.js'
export default {
mixins: [userPermission],
props: {
count: { // 最多选择图片张数,默认9张
type: Number,
default () {
return 9
}
},
uploadUrl: { // 图片上传后台接口
type: String,
default(){
return ''
}
},
isShow: { // 隐藏上传按钮
type: Boolean,
default(){
return true
}
},
showUrl: { // 上传图片对象(后台返回的图片对象)
type: Array,
default(){
return []
}
}
},
data() {
return {
detailPics: [], //上传的结果图片集合(组件显示图片对象)
isTakePhoto: false,
timer: null,
isFault: 0, // 记录上传图片失败个数
currRequestNum: 0, // 记录本次调用接口次数
currSelectPicNum: 0, // 记录本次选择上传图片个数
currUrl: [], //记录本次上传图片地址集合
baseUrl: ipConfig.baseUrl,
authorScope: 'scope.camera'
}
},
watch: {
showUrl: {
handler(newVal) {
if (!newVal) return;
this.detailPics = newVal
},
immediate: true
}
},
methods: {
// 删除图片
deletePic(e) {
console.log(e)
},
// 图片预览
previewImage(e) {
console.log(e, '预览')
},
// 上传图片
getTakePhoto() {
let that = this
if (that.count == that.detailPics.length) {
uni.showToast({
title: `至多上传${that.count} 张图片`,
mask: true,
duration: 500,
icon: 'error'
})
return false
}
uni.chooseMedia({
count: that.count - that.detailPics.length, // 最多可以选择的图片张数,默认9
mediaType:['image'],
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function(res) {
console.log(res)
that.currSelectPicNum = res.tempFiles.length
uni.showLoading({
title: '上传中...',
mask: true,
icon: 'loading'
})
res.tempFiles?.forEach(item => {
that.uploadimg({
url: ipConfig.baseUrl + that.uploadUrl, //这里是你图片上传的接口
path: item, //这里是选取的图片的地址数组
header: {
'content-type': 'application/x-www-form-urlencoded',
'wx-token': wx.getStorageSync('Swrh_token'),
"openId": wx.getStorageSync('Swrh_key').openId
}
});
})
},
})
},
//多张图片上传
uploadimg: function(data) {
var that = this
uni.uploadFile({
url: data.url,
filePath: data.path,
name: 'file',
header: data.header,
formData: {}, // 其他参数
success: (resp) => {
var picUrl = JSON.parse(resp?.data || '{}') //返回的结果,可能不同项目结果不一样
if (picUrl.code === 0) { //上传图片成功
let currUrl = picUrl?.url || ''
that.currUrl.push(currUrl)
that.currRequestNum = that.currRequestNum + 1
} else {
that.isFault = that.isFault + 1
that.currRequestNum = that.currRequestNum + 1
}
},
fail: (res) => {
that.isFault = that.isFault+1
that.currRequestNum = that.currRequestNum + 1
},
complete: () => {
if (that.currRequestNum === that.currSelectPicNum) {
uni.hideLoading();
if (that.isFault > 0) {
uni.showModal({
title: '温馨提示',
content: '检测到有' + that.isFault + '张图片上传失败,可能需要您重新上传',
showCancel: false,
confirmText: '我知道了'
})
} else {
uni.showToast({
title: '图片上传成功',
mask: true,
icon: 'success'
})
}
that.detailPics = that.currUrl.concat(that.detailPics)
that.$emit('myevent',that.detailPics) //结果返回调用的页面
}
}
});
},
}
}
</script>
<style lang="scss" scoped>
.image-list {
width: 100%;
@include flex-config();
margin-bottom: 10rpx;
}
.pic {
position: relative;
width: calc((100% - 30rpx) / 3);
height: 174rpx;
margin: 5rpx;
background-color: #fff;
border-radius: 4rpx;
}
.delete_btn {
position: absolute;
display: inline-block;
height: 60rpx;
width: 60rpx;
text-align: center;
line-height: 60rpx;
border-radius: 50% 0 0 50%;
font-size: 30rpx;
color: red;
background-color: RGBA(63, 60, 58, .6);
top: 0;
right: 0;
z-index: 3;
}
.img-item {
width: 100%;
height: 100%;
/* width: calc((100% - 30rpx) / 3); */
/* height: 174rpx;
margin: 5rpx;
background-color: #fff;
border-radius: 4rpx; */
}
/* 上传按钮 */
.chooseimg {
width: 174rpx;
height: 174rpx;
background: #f4f5f7;
border-radius: 4rpx;
display: flex;
justify-content: center;
align-items: center;
}
.weui-uploader__input-box {
width: 110rpx;
height: 110rpx;
@include font-info(#ECECEC,110rpx,500);
text-align: center;
line-height: 110rpx;
position: relative;
}
.weui-uploader__input-box::after {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
content: '';
width: 1rpx;
height: 100%;
background-color: $borderColor;
}
.weui-uploader__input-box::before {
content: '';
width: 100%;
height: 1rpx;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
position: absolute;
background-color: $borderColor;
}
</style>