小程序云开发如何实现图片上传及发表文字

所属分类: 网络编程 / JavaScript 阅读数: 646
收藏 0 赞 0 分享

微信给了我们存储空间以及图片上传的功能,我们怎么可以轻易放过呢?

先看看界面:

二话不说, 先实现界面:

<!--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 () {

 }
})

到此为止,功能就实现了。

那么,到此为止,点赞功能就基本完成了, 请看详细代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

jQuery LigerUI 使用教程表格篇(1)

ligerGrid是ligerui系列插件的核心控件,用户可以快速地创建一个美观,而且功能强大的表格,支持排序、分页、多表头、固定列等等
收藏 0 赞 0 分享

JavaScript中常用的运算符小结

JavaScript中常用的运算符小结,需要的朋友可以参考下。
收藏 0 赞 0 分享

深入理解JavaScript系列(13) This? Yes,this!

在这篇文章里,我们将讨论跟执行上下文直接相关的更多细节。讨论的主题就是this关键字。实践证明,这个主题很难,在不同执行上下文中this的确定经常会发生问题
收藏 0 赞 0 分享

javascript (用setTimeout而非setInterval)

javascript (用setTimeout而非setInterval)如果用setInterval 可能出现 下次调用会在前一次调用前调用
收藏 0 赞 0 分享

JavaScript中两个感叹号的作用说明

用两个感叹号的作用就在于,如果明确设置了o中flag的值(非null/undefined/0""/等值),自然test就会取跟o.flag一样的值;如果没有设置,test就会默认为false,而不是null或undefined
收藏 0 赞 0 分享

javascript写的简单的计算器,内容很多,方法实用,推荐

最近用javascript写了一个简单的计算器,自己测试感觉还好,代码都给了注释,非常不错,推荐大家学习。
收藏 0 赞 0 分享

js的表单操作 简单计算器

javascript写的简单的加减乘除计算器,里面涉及到一些方法还是很实用的哦,新手不要错过
收藏 0 赞 0 分享

Jquery中删除元素的实现代码

empty用来删除指定元素的子元素,remove用来删除元素,或者设定细化条件执行删除
收藏 0 赞 0 分享

javaScript 利用闭包模拟对象的私有属性

JavaScript缺少块级作用域,没有private修饰符,但它具有函数作用域。作用域的好处是内部函数可以访问它们的外部函数的参数和变量(除了this和argument
收藏 0 赞 0 分享

为JavaScript类型增加方法的实现代码(增加功能)

大家在js开发过程中有些功能已经满足不了我们的需求,或没有我们需要的功能,那么我们就可以自己扩展下,个性化js
收藏 0 赞 0 分享
查看更多