提交视频/图文封装(uniapp)

62 阅读2分钟
<template>
  <view class="page_bg_FAFAFA">
    <view class="padd-top48">
      <textarea v-model="title"  class="txtarea" placeholder="请输入你要上传的内容" placeholder-style="color:999;"></textarea>
    </view>
    <view class="cr-333 font_s32 font_w500 padd-left53 mar-top68 line-height100">
      图片/视频
    </view>
    <view class="up-page padd-left50 mar-top24">
      <!--图片-->
      <view class="show-box" v-for="(item,index) in imageList" :key="index">

        <image class="full" :src="item.tempFilePaths" :data-src="image" @tap="previewImage(item)">
        </image>
        <view class="delect-icon" @tap="delect(index)">
          <image class="full" :src="clearIcon" mode=""></image>
        </view>
      </view>
      <!--视频-->
      <view class="show-box" v-for="(item1, index1) in videoList" :key="index1">
        <video class="full" :src="item1"></video>
        <view class="delect-icon" @tap="delectVideo(index1)">
          <image class="full" :src="clearIcon" mode=""></image>
        </view>
      </view>
      <view v-if="VideoOfImagesShow" @tap="chooseVideoImage" class="box-mode">
        <image class="full" :src="selectfile" mode=""></image>
      </view>
    </view>
    <view class="btn" @click="addForum">
      提交
    </view>
  </view>
</template>

<script>
  var sourceType = [
    ['camera'],
    ['album'],
    ['camera', 'album']
  ];
  export default {
    data() {
      return {
        title: '',
        // 图标
        clearIcon: '/static/icon/del.svg',
        selectfile: '/static/icon/add.svg',
        VideoOfImagesShow: true, // 页面图片或视频数量超出后,拍照按钮隐藏
        imageList: [], //存放图片的地址
        videoList: [], //视频存放的地址
        sourceType: ['拍摄', '相册', '拍摄或相册'],
        sourceTypeIndex: 2,
        cameraList: [{
          value: 'back',
          name: '后置摄像头',
          checked: 'true'
        }, {
          value: 'front',
          name: '前置摄像头'
        }],
        cameraIndex: 1, //上传视频时的数量
        maxCount: 9, //图片和视频允许上传的总数

      };
    },
    onUnload() {
      (this.imageList = []), (this.sourceTypeIndex = 2), (this.sourceType = ['拍摄', '相册', '拍摄或相册']);
    },

    methods: {

      async addForum() {
        try {
          if (this.title === '' || (this.imageList.length === 0 && this.videoList.length === 0)) {
            uni.showToast({
              title: '请上传相关内容',
              icon: "error",

            })
            return;
          }
          let requestData = {
            title: this.title,
          };

          if (this.imageList.length > 0) {
            requestData.imageDtos = this.imageList.map(item => {
              console.log('item', item)
              return {
                ...item.updateRes,
                type: 1, // 设置图片类型为1
              }

            });
          }

          if (this.videoList.length > 0) {
           
            
            requestData.videoDtos = this.videoList.map(videoPath => {
              
              console.log('this.videoList11111', );
              debugger
              return {
                ...videoPath,
                type: 2, // 设置视频类型为2
              }
            });
          }

          const res = await this.$http.post('/yaolexue-service-portal/forum/addForum', requestData, {
            showLoading: true,
            isNeedLoading: true
          });
          console.log('Forum upload response:', res);


          this.imageList = [];
          this.VideoOfImagesShow = true;



          if (res.code == 200) {
            uni.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 2000,
            });
            uni.navigateTo({
              url: '/subPages/ylxService/ylxService'
            })
          }
        } catch (error) {

          console.error('Error uploading content:', error);
          uni.showToast({
            title: '上传失败,请重试',
            icon: 'none',
            duration: 2000,
          });
        }
      },
      //点击上传图片或视频
      chooseVideoImage() {
        uni.showActionSheet({
          title: '选择上传类型',
          itemList: ['图片', '视频'],
          success: res => {
            console.log(res);
            if (res.tapIndex == 0) {
              this.chooseImages();
            } else {
              this.chooseVideo();
            }
          }
        });
      },
      //上传图片
      chooseImages() {
        uni.chooseImage({
          count: this.maxCount, //允许选择的数量
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          success: res => {
            console.log('chooseImage', res);
            uni.showLoading({
              title: '上传中...',
              mask: true,
            });
            this.imageList = [...this.imageList, ...res.tempFilePaths.map(item => {
              return {
                tempFilePaths: item
              }
            })]

            console.log(this.imageList)
            this.imageList.forEach(item => {
              if (!item.updateRes) {
                uni.uploadFile({
                  url: this.$baseUrl + '/yaolexue-service-portal/minio/uploadImg',
                  header: {
                    Authorization: `Bearer ${uni.getStorageSync('token')}`
                  },
                  name: 'file',
                  filePath: item.tempFilePaths,
                  success: (e) => {
                    
                    item.updateRes = JSON.parse(e.data).data

                  },
                  fail: (error) => {
                    console.error('Upload failed:', error);
                  },
                  complete: () => {
                    // 隐藏加载动画
                    uni.hideLoading();
                  }
                })
              }

            })

            if (this.imageList.length + this.videoList.length == this.maxCount) {
              this.VideoOfImagesShow = false; //图片上传数量和count一样时,让点击拍照按钮消失
            }
          }
        })
      },
      //上传视频
      chooseVideo(index) {
        uni.chooseVideo({
          maxDuration: 60, //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒
          count: this.maxCount,
          camera: this.cameraList[this.cameraIndex].value, //'front'、'back',默认'back'
          sourceType: sourceType[this.sourceTypeIndex],
          success: res => {
            uni.showLoading({
              title: '上传中...',
              mask: true,
            });
            this.videoList = this.videoList.concat(res.tempFilePath);

            console.log(this.videoList)
            uni.uploadFile({
              url: this.$baseUrl + '/yaolexue-service-portal/minio/uploadImg',
              header: {
                Authorization: `Bearer ${uni.getStorageSync('token')}`
              },
              name: 'file',

              filePath: this.videoList[0],
              success: (e) => {
                const videoInfo = JSON.parse(e.data).data;
 
                    const blobUrlIndex = this.videoList.findIndex(item => item.compressLink === e.tempFilePath);

                    if (blobUrlIndex !== -1) {
                      this.videoList.splice(blobUrlIndex, 1, videoInfo);
                    }
                
                    

              },
              complete: () => {
                // 隐藏加载动画
                uni.hideLoading();
              }
            })
            if (this.imageList.length + this.videoList.length == this.maxCount) {
              this.VideoOfImagesShow = false;
            }

          }
        })
      },
      //预览图片
      previewImage: function(e) {
        console.log(e)
        uni.previewImage({
          current: e,
          urls: this.imageList
        });
      },
      // 删除图片
      delect(index) {
        uni.showModal({
          title: '提示',
          content: '是否要删除该图片',
          success: res => {
            if (res.confirm) {
              this.imageList.splice(index, 1);
            }
            if (this.imageList.length + this.videoList.length == this.maxCount) {
              this.VideoOfImagesShow = false;
            } else {
              this.VideoOfImagesShow = true;
            }
          }
        });
      },
      // 删除视频
      delectVideo(index) {
        uni.showModal({
          title: '提示',
          content: '是否要删除此视频',
          success: res => {
            if (res.confirm) {
              this.videoList.splice(index, 1);
            }
            if (this.imageList.length + this.videoList.length == this.maxCount) {
              this.VideoOfImagesShow = false;
            } else {
              this.VideoOfImagesShow = true;
            }
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .txtarea {
    width: 650rpx;
    height: 329rpx;
    background: #F3F3F3;
    border-radius: 20rpx;
    padding: 31rpx 26rpx;
    margin: auto;
    font-size: 30rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #333;
  }

  .upbox {
    width: 153rpx;
    height: 153rpx;
    background: #F3F3F3;
    border-radius: 20rpx;
    margin: 10rpx 8rpx 0 0;
  }

  .btn {
    width: 561rpx;
    height: 86rpx;
    background: #FA312A;
    border-radius: 43rpx;
    position: absolute;
    bottom: 150rpx;
    font-size: 32rpx;
    color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    left: 50%;
    transform: translateX(-50%);
  }

  .box-mode {
    width: 27vw;
    height: 27vw;

    border-radius: 8rpx;
    overflow: hidden;
  }

  .full {
    width: 100%;
    height: 100%;
  }

  .up-page {
    display: flex;
    flex-wrap: wrap;
    display: flex;
    width: 100%;

    .show-box:nth-child(3n) {
      margin-right: 0;
    }

    .show-box {
      position: relative;
      margin-bottom: 4vw;
      margin-right: 4vw;
      @extend .box-mode;

      .delect-icon {
        height: 40rpx;
        width: 40rpx;
        position: absolute;
        right: 0rpx;
        top: 0rpx;
        z-index: 1000;
      }
    }
  }
</style>