小程序雲開發如何實現圖片上傳及發表文字

這篇文章主要介紹了小程序雲開發教程,如何實現圖片上傳及發表文字,具有一定的參考價值,感興趣的小夥伴們可以參考一下

微信給了我們存儲空間以及圖片上傳的功能,我們怎麼可以輕易放過呢?

先看看界面:

二話不說, 先實現界面:

<!--pages/pulish/pulish.wxml-->
<view class='flexDownC'>
 <view class='flexDownC w100'> 
  <textarea class='input' bindinput='textInput' placeholder-style='margin-left:20rpx;' maxlength='500' placeholder='和大家一起分享你遇到的趣事,糗事吧' value='{{text}}' auto-focus auto-height></textarea>
 </view>

 <view class='btm flexSpaceBet w100 publishItem'>
  <image src='../../images/pic.png' class='pic' bindtap='doUpload'></image>
  <view class='pulishBtn' bindtap='pulish'> 發佈</view>
 
 </view>
 <!-- wx:for='{{imgUrl}}' -->
 <view class='flexCenter w100' wx:if='{{imgUrl}}'>
  <!-- <view wx:for='{{imgUrl}}' class='{{imgUrl.length == 1? "imgUrlClass1": imgUrl.length == 2? "imgUrlClass2": imgUrl.length == 3? "imgUrlClass3": "imgUrlClass4"}}' > -->
   <image src='{{imgUrl}}' class='w100' mode="aspectFit" ></image>
  <!-- </view> -->
  
 </view>
 <!-- <image class='w100' src='cloud://qiupihu-d1e452.7169-qiupihu-d1e452/1451.gif'></image> -->

</view>

wxss:

/* pages/pulish/pulish.wxss */


.input{
 font-size: 28rpx;
 color: #666;
 width: 100%;
 min-height: 60rpx;
 height: auto;
 border-radius: 10rpx;
 padding: 20rpx;
}

.fl{
 display: flex;
 justify-content: flex-start;
}

.pic{
 width: 64rpx;
 height: 64rpx;
 margin-left: 20rpx;
}

.w100{
 width: 100%;
}

.publishItem{
 margin-top: 80rpx;
 height: 80rpx;
 border-top: 1px solid #ea9518;
 border-bottom: 1px solid #ea9518;
}

.pulishBtn{
 width: 100rpx;
 height: 50rpx;
 color: #fff;
 font-size: 28rpx;
 background: #ea9518;
 border-radius: 0.1;
 text-align: center;
 font-weight: bold;
 margin-right: 20rpx;
 line-height: 50rpx;
}

.h100{
 height: 100rpx;
}


.imgUrlClass2{
 width: 50%;
}

.imgUrlClass1{
  width: 100%;
}


.imgUrlClass3{
  width: 33%;
}

.imgUrlClass4{
  width: 24%;
}

接下來就是js的代碼了:

我們要求發佈的人必須是已登錄狀態,這個可以查看本地是否有username得知

// pages/pulish/pulish.js
var app = getApp()
const db = wx.cloud.database()
const _ = db.command;
Page({

 /**
  * 頁面的初始數據
  */
 data: {
  text: '',
  imgUrl: '',
  count: 0
 },

 /**
  * 生命週期函數--監聽頁面加載
  */
 onLoad: function (options) {
  this.getCount()
  
 },
 onShow: function(){
  let userOpenId = wx.getStorageSync('openId')
  if (!userOpenId) {
   wx.showToast({
    title: '您還未登錄,請先登錄~',
    icon: 'none'
   })

   setTimeout(() => {
    wx.switchTab({
     url: '../me/me',
    })
   }, 1500)
  } else {
   console.log(userOpenId)
  }
 },
 getCount: function(){
 //已輸入的字數
  var that = this
  db.collection('funnys').count({
   success: res => {
    that.setData({
     count: Number(res.total) + 1
    })
   }
  })

 },
 textInput: function(e){
  this.setData({
   text: e.detail.value
  })
 },
 pulish: function(){

  var data = {
   image: new Array(app.globalData.fileID), //將圖片儲存爲數組類型
   content: this.data.text, //用戶輸入的文字
   comment: [],
   userId: wx.getStorageSync('userId'),
   username: wx.getStorageSync('username'), //用戶名
   id: Number(this.data.count) +1, //是現在數據庫的條數+1,微信小程序的不知道怎麼設置自增的數字字段
   shareNum: 0,
   commentNum: 0,
   validStatus: 0,
   validTime: 0
  }
  //validStatus: 審覈狀態, 通過時候 +1, 反對時候-1
  //validTime: 審覈次數, 最多5次,如果反對的人大於等於3,則不通過

  console.log(data)

  if (data.content){
   db.collection('funnys').add({
     data: data,
     success:res => {
      wx.showToast({
       title: '發佈成功',
      })
      setTimeout(()=>{
       
       wx.switchTab({
        url: '../index/index',
       })
      }, 1000)
     },
     fail: e=>{
      wx.showToast({
       title: '發佈錯誤',
      })
      console.log(e)
     }
    })
  }else{
   wx.showToast({
    title: '請填寫文字',
    icon: 'none'
   })
  }

 },

 // 上傳圖片
 //上傳的時候,我們可以獲得一個fileId,這個id我們必須存起來,在別人查看的時候,image的src使用的就是fileId,然後用戶必
 //須得知道上傳的是哪張圖片呀, 所以我們使用的是本地的圖片路徑來展示,即imagePath 
 doUpload: function () {
  // 選擇圖片
  var that = this;
  wx.chooseImage({
   count: 1,
   sizeType: ['compressed'],
   sourceType: ['album', 'camera'],
   success: function (res) {

    wx.showLoading({
     title: '上傳中',
    })

    const filePath = res.tempFilePaths[0]
    that.setData({
     imgUrl: filePath
    })
    // 上傳圖片
    const cloudPath = that.data.count + filePath.match(/\.[^.]+?$/)[0]
    //改寫: 數組 多圖片
    // const filePath = res.tempFilePaths, cloudPath = [];
    // filePath.forEach((item, i)=>{
    //  cloudPath.push(that.data.count + '_' + i + filePath[i].match(/\.[^.]+?$/)[0])
    // })
     
    console.log(cloudPath)


    // filePath.forEach((item, i) => {
     wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
       console.log('[上傳文件] 成功:', cloudPath, res)

       app.globalData.fileID = res.fileID
       app.globalData.cloudPath = cloudPath
       app.globalData.imagePath = filePath
       
      },
      fail: e => {
       console.error('[上傳文件] 失敗:', e)
       wx.showToast({
        icon: 'none',
        title: '上傳失敗',
       })
      },
      complete: () => {
       wx.hideLoading()
      }
     })
    // })

   },
   fail: e => {
    console.error(e)
   }
  })
 },
 /**
  * 用戶點擊右上角分享
  */
 onShareAppMessage: function () {

 }
})

到此爲止,功能就實現了。

那麼,到此爲止,點贊功能就基本完成了, 請看詳細代碼

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章