<template>
<view class="container">
<view class="image-list">
<view
class="image-item"
v-for="(image, index) in imageList"
:key="index"
>
<image :src="image" class="image-style"></image>
<view class="image-delete" @click="deleteImage(index)">删除</view>
</view>
<view class="add-image" @click="chooseImage">+</view>
</view>
<button @click="uploadImages">上传图片</button>
</view>
</template>
<script>
export default {
data() {
return {
imageList: [], // 存储选中的图片路径
};
},
methods: {
// 选择图片
chooseImage() {
uni.chooseImage({
count: 9, // 默认9, 设置图片的选择数量
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
this.imageList = [...this.imageList, ...tempFilePaths];
},
});
},
// 删除图片
deleteImage(index) {
this.imageList.splice(index, 1);
},
// 上传图片
uploadImages() {
if (!this.imageList.length) {
uni.showToast({
title: '请选择至少一张图片',
icon: 'none',
});
return;
}
const uploadTaskList = this.imageList.map((imagePath) => {
return uni.uploadFile({
url: 'https://your-api-upload-url', // 替换为你的上传API地址
filePath: imagePath,
name: 'file', // 这里根据API的要求来定义
formData: {
// 这里可以添加一些POST请求中的额外参数
},
success: (uploadFileRes) => {
console.log('图片上传成功', uploadFileRes);
},
fail: (error) => {
console.error('图片上传失败', error);
},
});
});
Promise.all(uploadTaskList).then(() => {
uni.showToast({
title: '图片上传成功',
icon: 'success',
});
}).catch(() => {
uni.showToast({
title: '图片上传失败',
icon: 'none',
});
});
},
},
};
</script>
<style scoped>
.container {
padding: 20px;
}
.image-list {
display: flex;
flex-wrap: wrap;
}
.image-item {
position: relative;
width: 120px;
margin-right: 10px;
margin-bottom: 10px;
}
.image-style {
width: 100%;
height: auto;
}
.image-delete {
position: absolute;
top: 0;
right: 0;
padding: 2px 5px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
font-size: 12px;
}
.add-image {
width: 120px;
height: 120px;
line-height: 12
评论已关闭