微信小程序--云开发仿QQ动态发布

前言

微信小程序的云开发非常适合初级开发者,特别是对传统后端不是了解的开发者非常友好,我们只需要根据开发文档查找对应的函数即可(当然,微信开发文档坑是非常的多啊,一定要小心!)

下面就用云开发做一个类似QQ发布动态的demo吧!

该博客解决的问题:

  1. 利用云开发上传图片
  2. 将图片保存在云数据库中
  3. 对用户内容的一些转换(回车换行等)
  4. 动态内容显示

demo

先上效果图(图一:发布界面 图二:动态界面) 在这里插入图片描述 在这里插入图片描述

代码详解

步骤一 准备发布界面,内容如下

  • 发布内容输入框
  • 选择图片
  • button确认发布

wxml


<cu-custom bgColor="bg-gradual-green" isBack="{{true}}">
  <view slot="backText">返回</view>
  <view slot="content">小助手</view>
</cu-custom>
<view class='UCenter-bg margin-top'>
  <image src='/images/taiyang.png' class='png' mode='widthFix'></image>
  <view class='text-xl text-black'>
    <text class='text-df'></text>
  </view>
  <image src='https://wx4.sinaimg.cn/mw690/006cV2kkly1g6j37v8m2lg30f002skhn.gif' mode='scaleToFill' class='gif-wave'></image>
</view>




<form bindsubmit="formSubmit" bindreset="formReset">




  <view class="cu-form-group margin-top margin-right margin-left">
    <textarea maxlength="-1" disabled="{{modalName!=null}}" placeholder="输入内容" value='' name='content'></textarea>
  </view>




  <view class="cu-bar bg-white margin-top margin-right margin-left">
    <view class="action">
      选择图片
    </view>
    <view class="action">
      {{imgList.length}}/9
    </view>
  </view>
  <view class="cu-form-group margin-right margin-left">
    <view class="grid col-3 grid-square flex-sub">
      <view class="bg-img" wx:for="{{imgList}}" wx:key="{{index}}" bindtap="ViewImage" data-url="{{imgList[index]}}">
        <image src='{{imgList[index]}}' mode='aspectFill'></image>
        <view class="cu-tag bg-red" catchtap="DelImg" data-index="{{index}}">
          <text class="cuIcon-close"></text>
        </view>
      </view>
      <view class="solids" bindtap="ChooseImage" wx:if="{{imgList.length<9}}">
        <text class="cuIcon-cameraadd"></text>
      </view>
    </view>
  </view>
  <!-- !!!!! placeholder 在ios表现有偏移 建议使用 第一种样式 -->
  <view class="padding-xl">
    <button class=" block bg-yellow lg" form-type="submit">
      OK </button>
  </view>
</form>

步骤二(关键部分) js部分获取用户输入的文字内容、选择图片的地址(便于上传至云数据库)

  • 获取用户输入文字内容 若为空 则提示用户重新输入
  • 获取用户选择图片 用数组存储 便于后面上传云数据库
  • 提交表单的时候 分成两部分:1、用户输入纯文字、无图片 2、有文字、图片

完整js太长了,这里就不放出了

重点说一下上传函数吧!

注意:( formSubmit(e)函数 非常重要,而且容易出错) 这里单独解释一下 formSubmit(e)函数 注释我就写在代码中了

formSubmit(e) {
// formSubmit是提交表单时需要执行的函数
    console.log(e.detail.value)// 输入内容
    console.log(this.data.imgList)// 图片地址
    var xx = util.imgname(new Date()) // 生成随机图片名字
    var time_1 = util.formatTime(new Date())
    var img_path = this.data.imgList//图片的路径
    var name = app.globalData.user_name//用户名,这里我是进入程序时 获取然后
                                   	// 放入全局变量的
    var imgpath = app.globalData.user_imgpath//用户的头像地址
    console.log(name)
    console.log(imgpath)
    // 用户输入内容时候,会有回车键 不做处理的话 数据库是不会存储的 
    // 解决方案就是:将获取的回车键用 &hc 代替
    // 获取记录的时候 再反代换即可
    var containt = e.detail.value.content.split('\n').join('&hc')//评论    

      if (containt.length != 0 ) {
        wx.showLoading({
          title: '上传中!',
        })

        // 没有上传图片 这里就比较简单 直接上传内容即可
        if (img_path.length == 0) {
          db.collection('communication').add({
            // data 字段表示需新增的 JSON 数据
            data: {
              user_name: name,
              user_img: imgpath,//用户头像地址
              user_containt: containt,//发布的内容
              user_imgpaht: [],//图片的云id
              time: time_1,// 发布时间
              see_num: 1,// 浏览人数
              comment_num: 0,// 评论总数
              fabulous_num: 0,//点赞人数
              },
            success: function (res) {
              setTimeout(function () {
                wx.hideLoading()
                wx.showToast({
                  title: '成功',
                  icon: 'success',
                  duration: 1000
                })
              }, 1000)
              setTimeout(function () {
                wx.navigateBack({
                  delta: 1
                })
              }, 3000)
            },
            fail: function (res) {
              setTimeout(function () {
                wx.hideLoading()
                wx.showToast({
                  title: '发布失败!',
                  icon: 'none',
                  duration: 1000
                })
              }, 1000)
            }
          })
        }
        
        // 有图片上传时候,这里就有点容易错了
        else {
        // temporary_path 用来存储图片的云id
        // 因为我们上传图片到云数据库时候 会获得一个云id
        // 这个云id 大家都可以用这个id访问图片
          var temporary_path = []
		
		// 利用for循环 依次上传图片 一次上传一张图片
          img_path.forEach((item, i) => {
         
          // x是图片的随机命名
            var x ="image/"+ Math.floor(Math.random() * 10000000).toString() + i + xx.toString() + '.jpg';
            console.log("图片的命名:"+x)
           
           //wx.cloud.uploadFile是云数据库上传函数 成功返回云id
            wx.cloud.uploadFile({
              cloudPath: x,
              filePath: img_path[i], // 文件路径
              success: res => {
                console.log(res.fileID)
                temporary_path.push(res.fileID)
                console.log(temporary_path)
                console.log(i)

				// 这里是非常容易错的地方
				// 微信小程序中的for循环 不同于c++的循环
				// 例如 for(i=0;i<5;i++)
				// 微信小程序中结果 可能是: 1 2 0 5 4 (随机的 没有规律)
				// 所以对我们判断图片上传完全没有 造成了很多的困难
				// 但是办法总是有的
				// 我们利用数组的长度判断就行了 
				// 只有获取的云id数组长度和图片数组长度一样 就说明上传完成了
			   // 上传完成图片后 就把数据写入记录 这个就很简单了 
                if ((img_path.length - 1) == temporary_path.length - 1) {

                  db.collection('communication').add({
                    // data 字段表示需新增的 JSON 数据
                    data: {
                      user_name: name,
                      user_img: imgpath,//用户头像地址
                      user_containt: containt,//发布的内容
                      user_imgpaht: temporary_path,//图片的云id
                       time: time_1,
                      see_num: 1,
                      comment_num: 0,
                      fabulous_num: 0,  
                    },
                    success: function (res) {
                      setTimeout(function () {
                        wx.hideLoading()
                        wx.showToast({
                          title: '成功',
                          icon: 'success',
                          duration: 1000
                        })
                      }, 1000)
                      setTimeout(function () {
                        wx.navigateBack({
                          delta: 1
                        })
                      }, 3000)

                    },
                    fail: function (res) {
                      setTimeout(function () {
                        wx.hideLoading()
                        wx.showToast({
                          title: '发布失败!',
                          icon: 'none',
                          duration: 1000
                        })
                      }, 1000)
                    }
                  })


                }
              },
              fail: err => {
                // handle error
              }
            })
          })
        }
      }
      
      else {
        wx.showToast({
          title: '请输入发布的内容!',
          icon: "none",
          duration: 1000
        }) }
  
    // console.log('form发生了submit事件,携带数据为:', e.detail.value)
  },

步骤三 然后就在动态界面 获取记录 显示记录(含图片) 这里注意的一点就是 获取的内容需要进行换行转换

    res.data[i].user_containt = res.data[i].user_containt.split('&hc').join('\n');   

而且需要显示换行,wxml放文字那里需要加上 white-space: pre-wrap

 <view class="" style="white-space: pre-wrap;">
  {{item.user_containt}}    
   </view>

我正在参加「创意开发 投稿大赛」详情请看:掘金创意开发大赛来了!

猜你喜欢

转载自juejin.im/post/7124956787563823134