123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- <template>
- <view class="image-upload">
- <!-- 显示已选择的图片 -->
- <view class="image-list">
- <view v-for="(image, index) in imageList" :key="index" class="image-item">
- <image :src="image" mode="aspectFill" class="image"></image>
- <view class="delete-btn" @click="deleteImage(index)">×</view>
- </view>
- </view>
- <!-- 选择图片按钮 -->
- <view class="upload-btn" @click="chooseImage">
- <text>+</text>
- </view>
- </view>
- </template>
- <script>
- export default {
- data() {
- return {
- imageList: [], // 存储已选择的图片路径
- };
- },
- methods: {
- // 打开相册选择图片
- chooseImage() {
- uni.chooseImage({
- count: 9, // 最多可以选择 9 张图片
- sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
- sourceType: ['album'], // 仅从相册选择
- success: (res) => {
- // 将选择的图片路径添加到 imageList 中
- this.imageList = this.imageList.concat(res.tempFilePaths);
- },
- fail: (err) => {
- console.error('选择图片失败', err);
- uni.showToast({
- title: '选择图片失败',
- icon: 'none',
- });
- },
- });
- },
- // 删除图片
- deleteImage(index) {
- this.imageList.splice(index, 1);
- },
- // 上传图片
- uploadImages() {
- if (this.imageList.length === 0) {
- uni.showToast({
- title: '请先选择图片',
- icon: 'none',
- });
- return;
- }
- // 遍历 imageList 上传每张图片
- this.imageList.forEach((imagePath) => {
- uni.uploadFile({
- url: 'https://your-upload-url.com/upload', // 替换为你的上传接口地址
- filePath: imagePath,
- name: 'file', // 文件对应的 key
- formData: {
- // 可以添加额外的表单数据
- userId: '123',
- },
- success: (uploadRes) => {
- console.log('上传成功', uploadRes);
- uni.showToast({
- title: '上传成功',
- icon: 'success',
- });
- },
- fail: (err) => {
- console.error('上传失败', err);
- uni.showToast({
- title: '上传失败',
- icon: 'none',
- });
- },
- });
- });
- },
- },
- };
- </script>
- <style scoped>
- .image-upload {
- display: flex;
- flex-wrap: wrap;
- }
- .image-list {
- display: flex;
- flex-wrap: wrap;
- }
- .image-item {
- position: relative;
- width: 100px;
- height: 100px;
- margin: 5px;
- }
- .image {
- width: 100%;
- height: 100%;
- border-radius: 5px;
- }
- .delete-btn {
- position: absolute;
- top: 0;
- right: 0;
- width: 20px;
- height: 20px;
- background-color: rgba(0, 0, 0, 0.5);
- color: white;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 16px;
- cursor: pointer;
- }
- .upload-btn {
- width: 100px;
- height: 100px;
- border: 1px dashed #ccc;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 24px;
- color: #ccc;
- margin: 5px;
- border-radius: 5px;
- }
- </style>
|