css
<van-cell-group inset>
<van-field name="uploader" label="附件信息" label-align="top">
<template #input>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="ViewImage"
:data-url="imgList[index]">
<image :src="imgList[index]" mode="aspectFill">
</image>
<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="ChooseImage" v-if="imgList.length < 4">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
</template>
</van-field>
</van-cell-group>
一些定义的类型
const imgList = ref([]) as any
const cipherMode = 1 //1 - C1C3C2,0 - C1C2C3,默认为1 用于sm2解密
const web_privateKey = import.meta.env.VITE_SM_WEB_PRIVATEKEY; //项目配置
注意:图中一些class属性是项目自带
上传文件的一些方法
点击查看大图方法
const ViewImage = (e) => {
uni.previewImage({
urls: imgList.value,
current: e.currentTarget.dataset.url
});
}
删除文件
const DelImg = (e) => {
uni.showModal({
content: '确定要删除这张图片吗',
cancelText: '再想想',
confirmText: '确定',
success: res => {
if (res.confirm) {
imgList.value.splice(e.currentTarget.dataset.index, 1)
const home = state.form.attachment.split(',')
for (let i = 0; i < home.length; i++) {
if (i === e.currentTarget.dataset.index) {
home.splice(e.currentTarget.dataset.index, 1);
}
}
state.form.attachment = home.toString()
}
}
})
}
//state.form.attachment 是给后端上传的属性
选择文件
const ChooseImage = () => {
uni.chooseImage({
count: 4, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
// sourceType: ['album'], //从相册选择
success: (res) => {
showLoadingToast({
message: '上传中...',
forbidClick: true,
duration: 0,
});
if (imgList.value.length != 0) {
imgList.value = imgList.value.concat(res.tempFilePaths)
} else {
imgList.value = res.tempFilePaths
}
upload(res)
// upload(res) 调取上传文件接口方法
},
fail: (res) => {
showFailToast(res.msg)
}
});
}
选择之后向服务器上传
const upload = (res: any) => {
uni.uploadFile({
//开发者服务器 url
url: ' /api/system/upload',
filePath: res.tempFilePaths[0],
header: {
'authorization': authStore.getAuthorization.authorization,
'functionFlag': 'app'
},
name: 'file',
success: (uploadFileRes) => {
closeToast();
let dataHex = uploadFileRes.data.substring(2).toLocaleLowerCase()
let decryptData = sm2.doDecrypt(dataHex, web_privateKey, cipherMode) // 解密结果
const Data = JSON.parse(decryptData)
console.log(Data, 'Data');
// let dataHex = uploadFileRes.data.substring(2).toLocaleLowerCase()
//let decryptData = sm2.doDecrypt(dataHex, web_privateKey, cipherMode) //解密结果
// const Data = JSON.parse(decryptData)
// console.log(Data, 'Data');
// sm2解密
if (state.form.attachment !== '' && state.form.attachment !== undefined && state.form.attachment !== null) {
state.form.attachment += ',' + Data.data.appendixId
} else {
state.form.attachment = Data.data.appendixId
}
showSuccessToast('上传成功')
},
fail: (err) => {
closeToast();
showFailToast(err.msg)
}
})
}