一、uniapp vue3.0+TS 上传单张或多张图片,并且能删除和预览。
效果:人菜话不多 先上效果:
二、代码
1.HTML 上传图片相关代码
代码如下:
<template>
<view class="images_box">
<view class="imgBox" v-for="(item, index) in fileList" :key="index">
<img class="image" :src="item.url" alt="" @click="previewImg(index)" />
<img @click.stop="delImges(item, index)" class="close" src="@/static/image/base/close.png" alt="删除" />
</view>
<view class="iconBox" @click="upload">
<u-icon name="plus" size="28" color="#438BEF"></u-icon>
</view>
</view>
</template>
2.TS上传图片相关代码
代码如下:
<script setup lang="ts">
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { examine } from "@/api";
const fileList = ref<any>([]);
const imgList = ref<any>([]);
const formState = reactive<any>({
conclusion: "",
suggestion: "",
task_id: null
});
const upload = () => {
uni.chooseImage({
count: 9, // 默认9
mediaType: ["image"],
sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
success: function (res: any) {
fileList.value = fileList.value.concat(res.tempFiles); //concat追加到数组
for (let file in fileList.value) {
up_img(fileList.value[file]);
}
},
});
};
const up_img = (file: any) => {
uni.uploadFile({
url: 'https://prod.XXX.com/XXXXX/XXX/XXXX/',
filePath: file.path,
name: 'files',
header: {
"Content-Type": "multipart/form-data"
},
success: (res: any) => {
let obj = JSON.parse(res.data);
imgList.value = [
...imgList.value,
{
type: obj.files[0].type,
size: obj.files[0].size,
name: obj.files[0].name,
url: 'https://prod.XXXXXX/XXXX/XXXX/XXXXX/' + obj.files[0].name,
}
];
fileList.value = imgList.value
uni.showToast({
title: '上传成功',
icon: "success",
});
},
fail: (res: any) => {
uni.showToast({
title: '上传失败',
icon: "error",
});
}
})
};
//删除图片
const delImges = async (rowItem: any, index: number) => {
fileList.value.forEach((item: any) => {
if (item.name == rowItem.name) {
fileList.value.splice(index, 1)
}
})
};
// 点击图片预览
const previewImg = (index: number) => {
let imgsArray = fileList.value.map((item: any) => {
return item.url
})
uni.previewImage({
urls: imgsArray,
current: index,
indicator: 'number',
loop: true
})
}
onLoad((options: any) => {
formState.task_id = Number(options.taskId)
});
</script>
3.CSS 上传图片相关代码
代码如下:
.images_box {
display: flex;
justify-items: flex-start;
flex-wrap: wrap;
.imgBox {
width: 120rpx;
height: 120rpx;
position: relative;
margin: 20rpx 20rpx 0 0;
.image {
width: 100%;
height: 100%;
border-radius: 10rpx;
}
.close {
width: 30rpx;
height: 30rpx;
position: absolute;
top: -15rpx;
right: -15rpx;
}
}
.iconBox {
width: 120rpx;
height: 120rpx;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10rpx;
border: 1px dashed gray;
box-sizing: border-box;
margin-top: 20rpx;
}
}