微信小程序云开发---vant组件 van-uploader 实现视频文件上传到云存储,发动态功能

pages/upVideo.wxml

//获取用户的头像和昵称展示
<view class="headerBox">
  <image src="{
     {userInfo.weixinInfo.avatarUrl}}"></image>
  <text>{
     {
     userInfo.weixinInfo.nickName}}</text>
</view>

//填写动态相关的信息,select为自定义的下拉选择组件
<view class="classifyBox">
   <input type="text" placeholder="课程标题(20个字以内)" value="{
     {title}}" maxlength="20" bindblur="titleBlur" bindinput="getInput"></input>
   <input type="digit" placeholder="课程价格" value="{
     {price}}" bindblur="priceBlur" bindinput="getPrice"></input>
    <select prop-array='{
     {selectList}}' selectText="选择课程分类" selectShow="{
     {select}}" bind:m_select_touch="m_select_touch"></select>
</view>

<view class="desc">
  <textarea focus="true" placeholder="课程简介" value="{
     {desc}}" maxlength="-1" placeholder-style="font-size:14px;color:#666" bindblur="descBlur" bindinput="getTextarea" />
</view>

<!-- 敏感内容警告提示节点 -->
<van-notify id="van-notify" />



<view class="imageRootAll">
<van-uploader
  file-list="{
     { fileList }}"
  accept="{
     {accept}}"
  multiple="true"
  compressed="false"
  bind:delete="Delete"
  bind:after-read="afterRead"
/>
</view>

<button type="primary" bindtap="publish">确认上传</button>

pages/upVideo.wxss

/* 头部信息 */
.headerBox{
     
  height:80px;
  width:100%;
  background:#fff;
  display: flex;
  align-items: center;
}
.headerBox image{
     
  height: 60px;
  width:60px;
  border-radius: 50%;
  margin:0px 20px;
}
.headerBox text{
     
  font-size:18px;
  color:#999;
}

/* 标题和分类 */
.classifyBox{
     
  width: 100%;
  height: 110px;
  /* margin:0px 2%; */
  background: #fff;
  border-top:1px solid #b1b1b1;
}
.classifyBox input{
     
  height: 30px;
  width: 90%;
  margin:5px 5%;
  font-size: 14px;
  border-bottom:1px solid #b1b1b1;
  
}


/* 详细内容 */
.desc{
     
  width:100%;
  height:200px;
  background:#fff;
  
}
.desc textarea{
     
  width:90%;
  margin:10px 5%;
  height:100%;
}
.imageRootAll{
     
  background:#fff;
  width:100%;
}
.imageRootAll van-uploader{
     
  width:98%;
  margin:1%;
  background:#fff;
}
button{
     
  margin:30px 10%;
  width:80%;
  height: 40px;
}

.showChoose{
     
  height: 200px;
  width:200px;
  margin-left:5%;
  background:#cdcdcd;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.showChoose image{
     
  width:60px;
  height:60px;
}
.showChoose view{
     
  color:#efefef;
}


/* 弹出层 */
van-popup{
     
  height: 100%;
  width:100%;
}
van-popup view{
     
     height: 20%;
    width:100%;
    text-align: center;
   /* line-height: 30%; */
}
van-popup .chooseImg{
     
  margin-top:2%;
}

pages/upVideo.json 。用到的vant 组件都是统一在全局app.json中引入的,这里就没必要重复引入了

{
     
  "usingComponents": {
     
    "select": "/components/select/select"
  }
}

到官网中下载,然后引入就可以,主要是引入路径的修改。
微信小程序云开发---vant组件 van-uploader 实现视频文件上传到云存储,发动态功能_第1张图片

pages/upVideo.js。图片上传和视频上传其实都是差不多的,定义一个临时存储的数组,然后对数组进行遍历,上传到云存储,保存云存储的存储路径保存到云数据库,改一下返回的一些参数就可以了。

const app=getApp();
const {
     days,TurnSecondPoints}=require('../../utils/getNowFormatDate.js');
const {
     hasSensitiveWords}=require('../../utils/contentdetection.js')
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
wx.cloud.init();
Page({
     

  /**
   * 页面的初始数据
   */
  data: {
     
    userInfo: [],//用户信息
    title: '', //课程标题
    desc: '', //课程内容简介
    classifyName: '', //标签分类
    price:"",//课程价格
    accept:'video',//上传内容格式,video
    fileList: [], //上传文件临时存储
    fileIDs: [],//文件上传后获取云数据中的位置
    selectList: [{
     
        name: '历史文化',
        id: 1
      },
      {
     
        name: '英语二外',
        id: 2
      },
      {
     
        name: '创课编程',
        id: 3
      },
      {
     
        name: '游学研学',
        id: 4
      },
      {
     
        name: '好书推荐',
        id: 5
      },
      {
     
        name: '健身瑜伽',
        id: 6
      },
      {
     
        name: '生活点滴',
        id: 7
      },
      {
     
        name: '成长点滴',
        id: 8
      },
      {
     
        name: '亲子关系',
        id: 9
      },
      {
     
        name: '职场技能',
        id: 10
      },
      {
     
        name: '学考公考',
        id: 11
      },
      {
     
        name: '家庭教育',
        id: 12
      },
      {
     
        name: '早教托班',
        id: 13
      },
      {
     
        name: '亲子关系',
        id: 14
      },
      {
     
        name: '职场技能',
        id: 15
      },
      {
     
        name: '感统训练',
        id: 16
      },
      {
     
        name: '复读学习',
        id: 17
      },
      {
     
        name: '语文',
        id: 18
      },
      {
     
        name: '数学',
        id: 19
      },
      {
     
        name: '英语',
        id: 20
      },
      {
     
        name: '音乐',
        id: 21
      },
      {
     
        name: '美术',
        id: 22
      },
      {
     
        name: '夏令营',
        id: 23
      },
      {
     
        name: '体适能',
        id: 24
      },
      {
     
        name: '专注力',
        id: 25
      },
      {
     
        name: '主持',
        id: 26
      },
      {
     
        name: '其他',
        id: 27
      }
    ],
    select: false,
    select_value1: {
     
      "id": "0",
      "text": "未选择"
    },

    // 选择图片
    show: false,


  },

  showPopup() {
     
    this.setData({
     
      show: true
    });
  },

  onClose() {
     
    this.setData({
     
      show: false
    });
  },

  // 获取内容标签分类
  m_select_touch(e) {
     
    let that = this;
    let selectIndex = e.detail.selIndex;
    console.log(that.data.selectList[selectIndex].name)
    that.setData({
     
      classifyName: that.data.selectList[selectIndex].name
    })
  },

//获取标题输入内容,并进行前端文本弱检测
  getInput(event) {
     
    let textVal = event.detail.value;
    if (hasSensitiveWords(textVal)) {
     
      Notify({
      type: 'warning', message: '含有敏感词,敏感词将会用*号处理' });
      this.setData({
     
        title: textVal.replace(textVal, "***")
      })
      console.log(this.data.title);
    } else {
     
      this.setData({
     
        title: textVal
      })
      console.log(this.data.title);
    }
  },
  // 标题云调用敏感内容检测
  titleBlur:function(){
     
    let that=this;
      wx.cloud.callFunction({
     
        name: 'msgSecCheck',
        data: {
     
         text: that.data.title
        },
        success(res){
     
          if(res.result.code == 500){
     
            Notify({
      type: 'warning', message: '内容包含违法违规词汇,禁止发布' });
             that.setData({
     
               title:''
             })
            
          }
        },
        fail(err){
     
          console.log(err)
        }
      })
  },

  // 价格
  priceBlur:function(){
     
    let that=this;
      wx.cloud.callFunction({
     
        name: 'msgSecCheck',
        data: {
     
         text: that.data.price
        },
        success(res){
     
          console.log(res)
          if(res.result.code == 500){
     
            Notify({
      type: 'warning', message: '内容包含违法违规词汇,禁止发布' });
             that.setData({
     
               price:''
             })
            
          }
        },
        fail(err){
     
          console.log(err)
        }
      })
  },
  // 课程价格云调用敏感内容检测
  getPrice:function(event){
     
    let textVal = event.detail.value;
    if (hasSensitiveWords(textVal)) {
     
      Notify({
      type: 'warning', message: '含有敏感词,敏感词将会用*号处理' });
      this.setData({
     
        price: textVal.replace(textVal, "***")
      })
      console.log(this.data.price);
    } else {
     
      this.setData({
     
        price: textVal
      })
      console.log(this.data.price);
    }
   
  },

  // 获取详细内容
  getTextarea(event) {
     
    let textVal = event.detail.value;
    if (hasSensitiveWords(textVal)) {
     
      Notify({
      type: 'warning', message: '含有敏感词,敏感词将会用*号处理' });
      this.setData({
     
        desc: textVal.replace(textVal, "***")
      })
      console.log(this.data.desc);
    } else {
     
      this.setData({
     
        desc: textVal
      })
      console.log(this.data.desc);
    }
   
  },
  // 详细内容云调用敏感内容检测
  descBlur:function(){
     
    let that=this;
      wx.cloud.callFunction({
     
        name: 'msgSecCheck',
        data: {
     
         text: that.data.desc
        },
        success(res){
     
          if(res.result.code == 500){
     
             Notify({
      type: 'warning', message: '内容包含违法违规词汇,禁止发布' });
             that.setData({
     
               desc:''
             })
            
          }
        },
        fail(err){
     
          console.log(err)
        }
      })
  },




  // 获取视频临时存储
  afterRead(event) {
     
    let that = this;
    // console.log(event)
    let obj = event.detail
    
    // console.log(obj)
    let NewfileList = {
     }
        NewfileList.url = obj.file.tempFilePath
        NewfileList.name = "video"+obj.index
        NewfileList.index=obj.index
        NewfileList.type = 'video'
        NewfileList.duration = obj.file.duration
        NewfileList.size=obj.file.size
    let fileList = []
      fileList.push(...that.data.fileList, NewfileList);
      that.setData({
     
        fileList
      })
    console.log(that.data.fileList)
  },

  // 删除其中一张图片
  Delete(event) {
     
    let that = this
    console.log(event)
    console.log(event.detail.index)
    wx.showModal({
     
      title: '要删除这个文件吗?',
      content: '',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
     
        if (res.confirm) {
     
          that.data.fileList.splice(event.detail.index, 1);
          that.setData({
     
            fileList: that.data.fileList
          })

        }
      }
    })
  },


   //上传数据
   publish() {
     
    let that=this
    var title=that.data.title;
    var price=that.data.price;
    var classifyName=that.data.classifyName;
    var desc = that.data.desc;
    var fileList = that.data.fileList;
    if (!title) {
     
      wx.showToast({
     
        icon: "none",
        title: '请输入课程标题'
      })
      return
  }
  if(!price) {
     
    wx.showToast({
     
      icon: "none",
      title: '请输入课程价格'
    })
    return
  }
  if(!classifyName) {
     
      wx.showToast({
     
        icon: "none",
        title: '请选择课程分类'
      })
      return
    }
    if (!desc || desc.length < 6) {
     
      wx.showToast({
     
        icon: "none",
        title: '请输入课程简介'
      })
      return
    }
    
    wx.showLoading({
     
      title: '正在上传...',
    })
    //遍历临时存储数组,实现上传
    const promiseArr = []
    for (let i = 0; i < that.data.fileList.length; i++) {
     
      let filePath = that.data.fileList[i].url
      let type=that.data.fileList[i].type
      let duration=TurnSecondPoints(that.data.fileList[i].duration)
      let title=that.data.fileList[i].name
      let index=that.data.fileList[i].index
      // console.log(filePath)
      let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式,获取文件扩展名
      //在每次上传的时候,就往promiseArr里存一个promise,只有当所有的都返回结果时,才可以继续往下执行
      promiseArr.push(new Promise((reslove, reject) => {
     
        wx.cloud.uploadFile({
     
          //'seriesLesson/'  是自定义云存储的文件夹位置,如果不加就是默认存储到云存储根目录下。
          cloudPath:'seriesLesson/'+new Date().getTime() + suffix,
          filePath: filePath, // 文件路径
        }).then(res => {
     
          // 获取上传的文件位置,存到fileID中
        //  console.log("上传结果", res.fileID)
          that.setData({
     
            fileIDs: that.data.fileIDs.concat({
     type:type,url:res.fileID,duration:duration,title:title,index:index})
          })
          
          reslove()
        }).catch(error => {
     
          console.log("上传失败", error)
        })
      }))
    }
    //保证所有文件都上传成功
    Promise.all(promiseArr).then(res => {
     
      var timestamp=(new Date()).getTime()
      wx.cloud.callFunction({
     
         name:'regist',
         data:{
     
           $url:'UploadVideo',
           avatarUrl:that.data.userInfo.weixinInfo.avatarUrl,
           nickName:that.data.userInfo.weixinInfo.nickName,
           level:that.data.userInfo.level,
           openId:that.data.userInfo.openId,
           company:that.data.userInfo.company,
           createTime:days(),//创建时间
           timestamp:timestamp,//当前时间戳
           className:classifyName,//内容标签
           coverTitle:title,//内容标题
           coverImg:that.data.fileIDs[0]?that.data.fileIDs[0].url:'',
           text:desc,//课程简介
         
           imgUrls:that.data.fileIDs?that.data.fileIDs:[],
           pay:true,
           price:Number(price)//课程价格
         },
         success: res => {
     
              wx.hideLoading()
              // wx.showToast({
     
              //   title: '发布成功',
              // })
              wx.cloud.callFunction({
     
                name:'regist',
                data:{
     
                  $url:'selectMycourses',
                  timestamp:timestamp
                },
                success:res=>{
     
                  // console.log(res.result.result.data[0]._id)
                   wx.cloud.callFunction({
     
                     name:'regist',
                     data:{
     
                       $url:'addMycourses',
                       openId:res.result.result.data[0].openId,
                       _id:res.result.result.data[0]._id
                     },
                     success(res){
     
                      //  console.log(res)
                     }
                   })
                }
              })
              wx.showModal({
     
                title: '提示',
                content: '上传成功,是否需要返回首页?',
                success (res) {
     
                  if (res.confirm) {
     
                    wx.switchTab({
     
                      url: '../home/home',
                    })
                  } else if (res.cancel) {
     
                    console.log('用户点击取消')
                  }
                }
              })
             
              
            },
          fail: err => {
     
              wx.hideLoading()
              wx.showToast({
     
                icon: 'none',
                title: '网络不给力....'
              })
              // console.error('发布失败', err)
            }

      })
     
    })
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
    let that = this;
    wx.getStorage({
     
      key: 'userInfo',
      success(res) {
     
        console.log(res)
        that.setData({
     
          userInfo: res.data
        })
      

      }
    })

  },

  // 点击发布动态


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
     
    console.log(this.data)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     
    console.log(this.data.fileList)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
     

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
     

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
     

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
     

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
     

  }
})

云函数 regist/index.js UploadVideo函数,云函数路由的使用在其他文章中有写

  app.router('UploadVideo', async (ctx) => {
     
    await db.collection('seriesLessons').add({
     
      data: {
     
        avatarUrl: event.avatarUrl,
        nickName: event.nickName,
        openId: event.openId,
        level: event.level,
        company: event.company,
        createTime: event.createTime, //创建时间
        timestamp: event.timestamp, //时间戳
        className: event.className, //内容标签
        coverTitle: event.coverTitle, //内容标题
        coverImg: event.coverImg,
        text: event.text, //内容详情
        media: {
     
          imgWidth: event.imgWidth,
          imgUrls: event.imgUrls
        }, //图片视频文件
        pay: event.pay,
        price:event.price,
        collection: [],
        dianzan: [],
        pinglun: [],
        zhuanfa: []
      },
      success(res) {
     
        ctx.body = {
     
          event,
          message: '动态发布成功'
        }
      }
    })
  });
  1. select 组件是一个自定义下拉选择内容的组件,根据个人情况使用。
  2. upVideo.js文件引入的敏感内容检测js在另一篇专门写这个的有写。
  3. 所有关于微信小程序云开发的文章都是在做了一个微信小程序云开发项目后的笔记总结,在开发过程中也有百度查资料,当时只顾着用来写项目,也就没有记下是参照了哪位大佬的文章了,厚颜说是原创,希望那些大佬们不要介意。
  4. 记录下这些东西一方面是做一下笔记,以后可能还用的上,另一方面也希望能帮到别人和得到大佬的指点。欢迎各位的指点和留言。

你可能感兴趣的:(微信小程序云开发,javascript,微信小程序)