微信小程序发布图文代码

这是第三个版本了。

通过promise异步实现发布多个图片,具体要发布图片,前端和js都需要改数量限制,最大值为9。

发现之前的方法已经过时,能用就行我也懒得换了,关于图片上传过大,影响上传速度以及主页展示渲染速度,影响体验,所以我加了一个压缩的方法。

小程序选择图片的一次或者多次选择,但是上传只能一张一张上传,使用使用promise和for循环实现,一张一张上传,上传一张后,返回图片在云存储的地址,然后把他保存到一个数组,一直拼接,直到for循环结束,为了方便云存储管理,我把路径做了动态管理,以年月日为路径。


Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    fileIDs: [],
    title: '',
    content: '',
    chongfu:true,//设置的timeout定时器防止短时间重复点击
    imgt:[],//图片压缩路径
    address:{}//使用request获取的地理位置信息
  },
  onLoad(options) {
 
  },
  title_input(e) {
   var title = e.detail.value
    console.log(title)
    this.setData({
      title: title
    })
  },
  content_input(e) {
   var content = e.detail.value
    console.log(content)
    this.setData({
      content: content
    })
  },
  //选择图片
  ChooseImage() {
    var that = this
    var promise1 = new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 9 - this.data.imgList.length, //默认9,我们这里最多选择6张
        sizeType: ['compressed'], //可以指定是原图还是压缩图,这里用压缩
        sourceType: ['album', 'camera'], //从相册选择
        success: (res) => {
          if (that.data.imgList.length != 0) {
            that.setData({
              imgList: that.data.imgList.concat(res.tempFilePaths)
            })
          } else {
            that.setData({
              imgList: res.tempFilePaths
            })
          }
          console.log("路径", that.data.imgList)
          console.log("选择图片成功", res)
          resolve()
        }
      });

    })
    Promise.all([promise1, ]).then(res => {
      for (var i = 0; i < that.data.imgList.length; i++) {
        wx.compressImage({ //图片压缩
          src: that.data.imgList[i], // 图片路径
          quality: 50 // 压缩质量
        }).then(res => {
          console.log("压缩成功", res)
          that.setData({
            imgt: that.data.imgt.concat(res.tempFilePath)
          })
          if (that.data.imgList.length - 1 == i)
            that.setData({
              imgList: that.data.imgt
            })
        })
      }
    })

  },
  //删除图片
  DeleteImg(e) {
    wx.showModal({
      title: '要删除这张照片吗?',
      content: '',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  //上传数据
  fabu(e) {
    var that = this
    that.setData({
      chongfu: false
    })
    setTimeout(function () {
      that.setData({
        chongfu: true
      })
    }, 2000);
    let account = wx.getStorageSync('account')
    //console.log(account)
    if (!account || !account.name) {
      wx.showToast({
        icon: 'error',
        title: '请先登陆',
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/demo04/demo04',
        })
      }, 1000);
      return
    }

    if (!that.data.content || that.data.content.length < 6) {
      wx.showToast({
        icon: "error",
        title: '内容必须大于6个字'
      })
      return
    }
    wx.showLoading({
      title: '发布中...',
    })
    wx.request({
      url: 'https://ip.useragentinfo.com/json',
      success: function (res) {
        ///console.log(res.data)
        that.setData({
          address:res.data
        })       
      }
    })
    var date = new Date();
    var Y = date.getFullYear();
    var M = date.getMonth() + 1;
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours()
    var min = date.getMinutes()
    var second=date.getSeconds()
    if (min < 10) {
      min = '0' + min
    }
    if (M < 10) {
      M = '0' + M
    }
    var tiezi_fabu_time ={}
    tiezi_fabu_time.Y=Y
    tiezi_fabu_time.M=M
    tiezi_fabu_time.D=D
    tiezi_fabu_time.H=H
    tiezi_fabu_time.min=min
    var langtime=Date.parse(new Date())

    // let tiezi_fabu_time = Y + "-" + M + "-" + D + " " + H + ":" + min
    const promiseArr = []
    //只能一张张上传 遍历临时的图片数组
    for (let i = 0; i < that.data.imgList.length; i++) {
      let filePath = that.data.imgList[i]
      let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式,获取文件扩展名
      //在每次上传的时候,就往promiseArr里存一个promise,只有当所有的都返回结果时,才可以继续往下执行
      promiseArr.push(new Promise((reslove, reject) => {
        wx.cloud.uploadFile({
          cloudPath: '图片/帖子/帖子上传图片/' + Y + '/' + M + '/' + D + '/' + new Date().getTime() + suffix,
          filePath: filePath, // 文件路径
        }).then(res => {
          // get resource ID
          console.log("上传结果", res.fileID)
          that.setData({
            fileIDs: that.data.fileIDs.concat(res.fileID)
          })
          reslove()
        }).catch(error => {
          console.log("上传失败", error)
        })
      }))
    }
    //保证所有图片都上传成功
    let db = wx.cloud.database()
    Promise.all(promiseArr).then(res => {
      db.collection('tiezi').add({
        data: {
          title: that.data.title,
          content: that.data.content,
          tiezi_fabu_time: tiezi_fabu_time,
          touxiangurl: wx.getStorageSync('account').touxiangurl,
          imageurl: that.data.fileIDs,
          account_id: wx.getStorageSync('account')._id,
          name: wx.getStorageSync('account').name,
          address:that.data.address,
          school: that.data.school,
          langtime:langtime,
          dianzan:0,
          shoucang:0,
          comments: [],

        },
        success: res => {
          wx.hideLoading()
          wx.showToast({
            title: '发布成功',
          })
          //清空数据
          this.setData({
            imgList: [],
            fileIDs: [],
          })
          console.log('发布成功', res)
          wx.navigateBack({
            delta: 1,
          })
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            icon: 'error',
            title: '网络不给力....'
          })
          console.error('发布失败', err)
        }
      })
    })
  },







})

  <view style="margin: 25rpx;display: flex;flex-direction: column;background-color: #ffffff;padding: 20rpx;border-radius: 35rpx;">
    <view style="display: flex;flex-direction: row;justify-content: space-between;width: 100%;align-items: center;">
      <input bindinput="title_input" placeholder="标题可有可无" style="width: 90%;padding-bottom: 15rpx;" maxlength="15" />
    </view>
    <textarea bindinput="content_input" placeholder="重要的是分享你的想法..." type="text" maxlength="500" style="word-break: break-all;white-space: pre-wrap;;width: 100%;padding-top: 15rpx;border-top: 1px solid #f5f5f5;"></textarea>
  </view>
  <view style="background-color: #ffffff;padding: 30rpx;margin: 25rpx;border-radius: 40rpx;">
    <view class="imageRootAll">
      <block wx:for="{{imgList}}" wx:key="index">
        <view class="imgItem">
          <image class="img" src='{{item}}' mode='aspectFill'></image>
          <image class="closeImg" bindtap="DeleteImg" src="/images/close.png" data-index="{{index}}" />
        </view>
      </block>
      <!-- 选择图片按钮 -->
      <view wx:if="{{imgList.length<6}}" class="imgItem" bindtap="ChooseImage">
        <image class="photo" src="../../images/photo.png"></image>
      </view>
    </view>
  </view>
  <view style="justify-content: center;display: flex;">
    <view bindtap="{{chongfu==true?'fabu':''}}" style="word-break: keep-all;color: #ffffff;background-color: #0052FA;padding: 12rpx 20rpx 12rpx 20rpx;border-radius: 40rpx;font-size: 35rpx;width: 140rpx;text-align: center;">publish</view>
  </view>

page {
  background-color: #F3F4F9;
}
.fabu {
  display: flex;
  float: right;
  margin-right: 10rpx;
  color: #A9A9A9;
  font-size: 40rpx;
}
.title_input {
  width: 100%;
  border-bottom: 1px solid #DCDCDC;
  margin: 30rpx;
}
.content_input {
  margin: 30rpx;
}
.img_box {
  display: flex;
  flex-wrap: wrap;
  margin: 0rpx;
}
.img_item_i {
  display: block;
  width: 100%;
  height: 100%;
}
.img_item {
  width: 210rpx;
  height: 210rpx;
  position: relative;
  margin-right: 2%;
  margin-bottom: 2%;
  border: 1px solid #c0ccda;
}
.closeImv {
  position: absolute;
  right: 0rpx;
  top: 0rpx;
  width: 35rpx;
  height: 35rpx;
  color: #fff;
  background-color: red;
  border-radius: 50%;
  text-align: center;
  line-height: 30rpx;
  font-weight: 600;
}

.imageRootAll {
  margin: 6rpx;
  display: flex;
  display: -webkit-flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}
.imgItem {
  margin: 6rpx;
  position: relative;
  width: 200rpx;
  height: 200rpx;
  background: gainsboro;
  margin-top: 50rpx;
}
.img {
  width: 100%;
  height: 100%;
}
.closeImg {
  position: absolute;
  right: 0px;
  width: 40rpx;
  height: 40rpx;
}
.photo {
  width: 50%;
  height: 50%;
  margin: 25%;
}

就到这里。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值