绿满眶商城微信小程序-uniapp
xiangpei
2025-06-12 e220ffde8924dbfd2319012f5aef83865244bc22
发布视频支持图片
1个文件已修改
1个文件已添加
329 ■■■■ 已修改文件
pages/tabbar/index/home1.vue 144 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pages/tabbar/video/video.vue 185 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pages/tabbar/index/home1.vue
New file
@@ -0,0 +1,144 @@
<template>
  <!-- 自定义控制条 -->
  <view
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      class="container">
    <!-- 进度条 - 整个区域可拖动 -->
    <view class="process-warp" :style="{ opacity: showProcess ? 1 : 0 }">
        <!-- 显示当前进度 -->
        <view class="progress-text">{{ hasPlayTime }}/{{formartDuration}}</view>
        <view
          class="progress-bar"
          id="progressBar"
        >
          <!-- 已填充部分 -->
          <view class="progress-fill" :style="{ width: progress + '%' }"></view>
        </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      startX: 0,
      progress: 0, // 视频进度
      startProgress : 0, // 开始滑动时的进度
      barLeft: 0, // 进度条左边界位置
      barWidth: 0, // 进度条宽度
      isDragging: false, // 是否正在拖动
      processHidenTimer: null, // 进度条隐藏定时器
      showProcess: false, // 是否显示进度条
    };
  },
  mounted() {
    // 获取进度条的尺寸和位置信息
    this.getBarRect();
  },
  methods: {
    // 获取进度条的位置和尺寸
    getBarRect() {
      const query = uni.createSelectorQuery().in(this);
      query.select('#progressBar').boundingClientRect(rect => {
        if (rect) {
          this.barLeft = rect.left;
          this.barWidth = rect.width;
        }
      }).exec();
    },
    // 触摸开始
    handleTouchStart(e) {
      this.isDragging = true;
      this.showProcess = true;
      this.startProgress = this.progress; // 记录开始时的进度
      this.startX = e.touches[0].pageX;
      console.log("记录开始时的进度", this.startProgress);
      this.videoContexts[this.currentIndex].pause()
      // this.updateProgress(e);
    },
    // 触摸移动
    handleTouchMove(e) {
      if (!this.isDragging || !this.barWidth) return;
      clearTimeout(this.processHidenTimer)
      this.videoContexts[this.currentIndex].pause()
      this.updateProgress(e);
    },
    // 触摸结束
    handleTouchEnd() {
      this.isDragging = false;
      console.log("滑动结束", this.duration * this.progress);
      this.videoContexts[this.currentIndex].seek(this.duration * this.progress / 100)
      this.videoContexts[this.currentIndex].play()
      this.processHidenTimer = setTimeout(() => {
          this.showProcess = false;
        }, 1000);
    },
    // 更新进度
    updateProgress(e) {
        // 获取当前触摸点X坐标
        const currentX = e.touches[0].pageX;
        // 计算滑动距离(像素)
        const deltaX = currentX - this.startX;
        // 将像素距离转换为进度增量
        const deltaProgress = (deltaX / this.barWidth) * 100;
        console.log("进度增量", deltaProgress);
        // 计算新进度 = 开始时的进度 + 滑动增量
        let newProgress = this.startProgress + deltaProgress;
        // 限制范围在0-100之间
        newProgress = Math.max(0, Math.min(100, newProgress));
        this.progress = newProgress;
    }
  }
};
</script>
<style>
.container {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: absolute;
      bottom: 0;
      width: 100%;
    }
    .progress-bar {
      position: relative;
      width: 100%;
      height: 16px;
      background-color: #eee;
      overflow: hidden;
    }
    .progress-fill {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      background-color: lightgray;
      transition: width 0.1s;
    }
    .process-warp {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .progress-text {
      margin-top: 10px;
      font-size: 14px;
      color: #666;
    }
</style>
pages/tabbar/video/video.vue
@@ -1,14 +1,20 @@
<template>
  <view class="publish-container">
    <u-popup v-model="fileTypeShow" mode="bottom"  round="20" height="35%">
        <view style="width: 100%;height:100%;display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <view>请选择要发布的类型</view>
            <u-button style="width: 50%;margin-bottom: 30rpx;margin-top: 20rpx;" type="success" @click="chooseVideo">视频</u-button>
            <u-button style="width: 50%;" type="success" @click="chooseImgs">图片</u-button>
        </view>
    </u-popup>
    <!-- 视频上传区域 -->
    <view class="upload-section">
      <view class="upload-btn" @click="chooseVideo" v-if="!videoInfo.url">
      <view class="upload-btn" @click="this.fileTypeShow = true" v-if="!formData.videoFileKey && formData.videoImgs.length < 1">
        <u-icon name="plus" size="40" color="#999"></u-icon>
        <text class="upload-text">点击上传视频</text>
        <text class="upload-tips">支持MP4格式,最长60秒</text>
        <text class="upload-text">点击上传</text>
      </view>
      
      <view class="video-preview" v-else>
      <view class="video-preview" v-else-if="formData.videoContentType === 'video'">
        <video 
          :src="videoInfo.url" 
          :object-fit="formData.videoFit"
@@ -20,7 +26,25 @@
        </view>
        <view class="video-actions">
          <u-button type="error" size="mini" @click="reUpload">重新上传</u-button>
          <u-button type="primary" size="mini" @click="chooseCover" v-if="videoInfo.url">{{formData.cover ? '更换封面' : '请选择封面'}}</u-button>
          <u-button type="primary" size="mini" @click="chooseCover" v-if="formData.videoFileKey">{{formData.cover ? '更换封面' : '请选择封面'}}</u-button>
        </view>
      </view>
      <view class="image-list" v-else-if="formData.videoContentType === 'img'">
        <view
          v-for="item in videoPreviewImgs"
          :key="item"
          class="image-item"
          :style="{width: itemWidth + 'px', height: itemWidth + 'px'}"
        >
          <image
            :src="item"
            mode="aspectFill"
            class="image"
          />
        </view>
        <view class="video-actions">
          <u-button type="error" size="mini" @click="reUpload">重新上传</u-button>
        </view>
      </view>
    </view>
@@ -120,7 +144,7 @@
    <!-- 发布按钮 -->
    <view class="publish-btn">
      <u-button 
        type="primary"
        type="success"
        shape="circle" 
        :loading="loading"
        @click="handlePublish"
@@ -188,14 +212,17 @@
  components: {MyTag,UIcon,UButton,UForm,UFormItem,UInput,USearch,UPopup},
  data() {
    return {
      fileTypeShow: false,
      cosClient: null,
      bucket: '',
      region: '',
      endpoint: '',
      videoUploadProgress: 0,
      loading: false,
      showGoodsPicker: false,
      goodsSearch: '',
      tagInput: '',
      videoPreviewImgs: [], // 预览图片地址
      videoInfo: {
          url: '',
          fileKey: '',
@@ -212,6 +239,8 @@
        videoDuration: 0,
        videoFit: 'cover',
        goodsId: '',
        videoContentType: 'video',
        videoImgs: [],
        tags: [],
        fileInfo: {}
      },
@@ -236,12 +265,18 @@
          { required: true, message: '请输入视频标题', trigger: 'blur' },
          { min: 1, max: 20, message: '标题长度在1到20个字符', trigger: 'blur' }
        ]
      }
      },
      screenWidth: 375,
      gap: 10 // 图片间距
    };
  },
  computed: {
    canPublish() {
        if(this.formData.videoContentType === 'video') {
      return this.formData.videoFileKey && this.formData.title && this.formData.cover;
        } else if(this.formData.videoContentType === 'img') {
            return this.formData.videoImgs.length > 0 && this.formData.title;
        }
    },
    filteredGoods() {
      if (!this.goodsSearch) return this.goodsList;
@@ -251,10 +286,16 @@
    },
    showTopicRecommendations() {
      return (this.tagInput === '' || this.recommendedTags.length > 0) && this.formData.tags.length < 5;
    },
    // 计算每个图片项的宽度(考虑间距)
    itemWidth() {
      return (this.screenWidth - (this.gap * 4) - 20) / 3
    }
  },
  created() {
  onLoad() {
    // 获取屏幕宽度
    const systemInfo = uni.getSystemInfoSync()
    this.screenWidth = systemInfo.windowWidth
  },
  onShow() {
      this.initCOS()
@@ -290,11 +331,17 @@
               });
               this.bucket = res.data.data.bucket
               this.region = res.data.data.region
               this.endpoint = res.data.data.endpoint
          })
          
      },
    // 选择视频
    chooseVideo() {
      this.fileTypeShow = false;
      // 清空选择的图片
      this.videoPreviewImgs = [];
      this.formData.videoImgs = [];
      this.formData.videoContentType = 'video'
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
@@ -374,15 +421,48 @@
    },
    // 重新上传
    reUpload() {
      this.videoInfo = {
        url: '',
        cover: '',
        duration: 0,
        size: 0
      };
      this.chooseVideo();
      this.resetData()
      this.fileTypeShow = true
    },
    // 选择视频图集
    chooseImgs() {
      this.fileTypeShow = false
      // 清空选择的视频
      this.formData.videoFileKey = '';
      this.formData.cover = '';
      this.formData.videoContentType = 'img'
      uni.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: (res) => {
          res.tempFilePaths.forEach(tmpImg => {
              let fileName = tmpImg.substring(tmpImg.lastIndexOf('/') + 1);
              // 处理安卓可能的URI编码
              if(fileName.indexOf('%') > -1) {
                              fileName = decodeURIComponent(fileName);
              }
              const fileKey = getFileKey(fileName);
              this.cosClient.uploadFile({
                   Bucket: this.bucket,
                   Region: this.region,
                   Key: fileKey,
                   FilePath: tmpImg,
                   SliceSize: 1024 * 1024 * 5     /* 触发分块上传的阈值,5M */
               }, (err, data) => {
                   if (err) {
                     console.log('上传失败', err);
                   } else {
                       // 获取封面的访问地址
                     this.videoPreviewImgs.push(this.endpoint + '/' + fileKey);
                     this.formData.videoImgs.push(fileKey);
                   }
               });
          })
    
        }
      });
    },
    // 选择封面
    chooseCover() {
      uni.chooseImage({
@@ -407,11 +487,8 @@
               if (err) {
                 console.log('上传失败', err);
               } else {
                   // 获取封面的访问地址
                   getFilePreviewUrl(fileKey).then(res => {
                   this.videoInfo.cover = res.data.data
                   this.videoInfo.cover = this.endpoint + '/' + fileKey
                   this.formData.cover = fileKey
                   })
               }
           });
        }
@@ -508,25 +585,7 @@
              });
              this.loading = false
              // 重置表单
              this.videoInfo = {
                    url: '',
                    fileKey: '',
                    fileType: '',
                    fileSize: 0,
                    originalFileName: '',
                    cover: ''
              };
              this.formData = {
                id: '',
                title: '',
                videoFileKey: '',
                cover: '',
                videoFit: 'cover',
                videoDuration: 0,
                goodsId: '',
                tags: [],
                fileInfo: {}
              };
              this.resetData();
              this.selectedGoods = null;
              this.tagInput = '';
              this.recommendedTags = [];
@@ -545,6 +604,31 @@
          });
        }
      });
    },
    resetData() {
        // 重置表单
        this.videoInfo = {
              url: '',
              fileKey: '',
              fileType: '',
              fileSize: 0,
              originalFileName: '',
              cover: ''
        };
        this.formData = {
          id: '',
          title: '',
          videoFileKey: '',
          cover: '',
          videoFit: 'cover',
          videoDuration: 0,
          goodsId: '',
          videoContentType: 'video',
          videoImgs: [],
          tags: [],
          fileInfo: {}
        };
        this.videoPreviewImgs = []
    }
  }
};
@@ -552,14 +636,13 @@
<style scoped>
.publish-container {
  padding: 20rpx;
  padding: 10px;
  padding-bottom: 120rpx;
}
.upload-section {
  background-color: #f8f8f8;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: center;
@@ -599,9 +682,11 @@
}
.video-actions {
  width: 100%;
  margin-top: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
}
@@ -767,4 +852,22 @@
    height: 25px;
    margin-top: 10px;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.image-item {
  margin: 5px;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
.image {
  width: 100%;
  height: 100%;
}
</style>