小程序云开发上传及使用图片

简介: 小程序云开发上传及使用图片

推荐一个不错的学习资料库

小程序云开发上传及使用图片

.wxml
<view class="img-view">
  <view class="show" wx:for="{{ imgOne }}" wx:key="_id">
    <image src="{{ item }}" mode="aspectFill" data-index="{{index}}" bindtap="previewImg"></image>
    <image class="del-img" src="../../images/icons/close.png" data-index="{{index}}" bindtap="reBackImg"></image>
  </view>
  <view class="up" wx:if="{{imgOneSwitch}}" bindtap="onChooseOne">+</view>
</view>
<button class="onSavebut" bindtap="onSave">发布</button>
.wxss
/* 上传图片 */
.img-view {
  width: 710rpx;
  margin: 20rpx 20rpx;
  /* background-color: red; */
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.img-view .up, .img-view .show {
  margin: 6rpx;
}
.img-view .up {
  height: 220rpx;
  width: 220rpx;
  background-color: #ededed;
  line-height: 200rpx;
  text-align: center;
  font-size: 100rpx;
  color: #bfbfbf;
}
.img-view .show {
  width: 220rpx;
  height: 220rpx;
  /* background-color: red; */
  position: relative;
}
.del-img {
  position: absolute;
  top: 0rpx;
  right: 0rpx;
  box-sizing: border-box;
  padding: 8rpx;
  background-color: #fff;
  border-bottom-left-radius: 10rpx;
  height: 50rpx !important;
  width: 50rpx !important;
  z-index: 9998;
}
.img-view .show image {
  width: 100%;
  height: 100%;
}
.onSavebut {
  width: 300rpx;
  color: #fff;
  background-color: #07C160;
}
.js
Page({
  data: {
    imgOneSwitch: true,
    imgOne: [],
    MAXCOUNTIMAGE: 9,   // 可以上传img数量
  },
  onLoad: function (options) {
  },
  // 保存到 存储 & 数据库
  onSave: function () {
    if (this.data.imgOne.length == 0) {
      wx.showToast({
        title: '请添加图片',
        icon: 'none'
      })
      return
    }
    console.log('通过 ---空--- 校验')
    wx.showToast({
      title: '上传图片中',
      icon: 'loading',
      duration: 30000,
      mask: true
    })
    this.OnUpImg()
  },
  OnUpImg: function () {
    let promiseArr = []
    let fileIds = []     // 将图片的fileId存放到一个数组中
    let imgLength = this.data.imgOne.length;
    // 图片上传
    for (let i = 0; i < imgLength; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.imgOne[i]
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({    
          cloudPath: 'testdir/' + Date.now() + '-' + Math.random() * 1000000 + suffix, 
          filePath: item,
          success: (res) => {
            console.log(res);
            // console.log(res.fileID)
            fileIds = fileIds.concat(res.fileID)       // 拼接
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    }
    Promise.all(promiseArr)
      .then((res) => {
        this.addtoDB(fileIds)
      })
      .catch((err) => {
        console.error(err)       // 上传图片失败
        wx.showToast({
          title: '上传失败 请再次点击发布',
          icon: 'none',
          duration: 3000
        })
      })
  },
  addtoDB: function (fileIds) {
    wx.showToast({
      title: '发布中...',
    })
  },
  // 选择图片 + 回显 
  onChooseOne: function () {
    let that = this
    wx.chooseImage({
      count: this.data.MAXCOUNTIMAGE - this.data.imgOne.length,
      // sizeType: ['compressed','original'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      // sourceType: ['album'],
      success(res) {
        console.log(res)
        let tempArr = that.data.imgOne.concat(res.tempFilePaths)
        that.setData({
          'imgOne': tempArr
        })
        if (that.data.imgOne.length >= that.data.MAXCOUNTIMAGE) {
          that.setData({
            imgOneSwitch: false
          })
        }
      }
    })
  },
  // 删除图片功能
  reBackImg: function (e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    console.log(index)
    let arr = this.data.imgOne
    arr.splice(index, 1)
    if (arr.length < this.data.MAXCOUNTIMAGE && this.data.imgOneSwitch === false) {
      this.setData({
        imgOneSwitch: true
      })
    }
    this.setData({
      imgOne: arr
    })
  },
  // 预览图片
  previewImg: function (e) {
    console.log('放大图片')
    let index = e.currentTarget.dataset.index
    let item = this.data.imgOne[index]
    console.log(item)
    wx.previewImage({
      current: item, // 当前显示图片的http链接
      urls: this.data.imgOne // 需要预览的图片http链接列表
    })
  },
})

参考:

微信小程序 云开发 上传多张图片 9宫格

使用

如果是做商城发布功能,有图片和其他字段,这个时候图片的存储地址也得传入云数据库,所以先把图片传入云存储,再把图片云存储的地址作为数据和其他字段一同传到云数据库,下面是我注册店铺的一个过程,大家可以看看。

// pages/main/addshop/addshop.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgOneSwitch: true,
  imgOne: [],
  MAXCOUNTIMAGE: 1,
    storeName: '',          // 店铺名称
    storeBrief: '',         // 店铺简介
    storeUser: '',          // 店主
    storeUserPhone: '',     // 店主联系方式
  },
  getStoreName(e) {
    this.setData({
      storeName:e.detail
    })
  },
  getBrief(e) {
    this.setData({
      storeBrief:e.detail
    })
  },
  getStoreUser(e) {
    this.setData({
      storeUser:e.detail
    })
  },
  getStoreUserPhone(e) {
    this.setData({
      storeUserPhone:e.detail
    })
  },
  // 点击提交注册
  submitStoreMessage () {
    this.onSave() // 头像放在云存储
  },
  addStore(){
    // 添加数据
    wx.cloud.database().collection('registerStore')
    .add({
      data: {
        url: this.data.imgOne[0],
        sroreName: this.data.storeName,
        storeBrief: this.data.storeBrief,
        storeUser: this.data.storeUser,
        storeUserPhone: this.data.storeUserPhone,
        allshopping: 111,
        Collection: 222
      }
    }).then(res => {
      console.log('注册成功',res);
    }).catch(err => {
      console.log('注册失败',err);
      wx.showToast({
        title: '注册失败',
        icon: 'none',
        duration: 3000
      })
    })
  },
  // 保存到 存储 & 数据库
  onSave: function () {
    if (this.data.imgOne.length == 0) {
      wx.showToast({
        title: '请添加图片',
        icon: 'none'
      })
      return
    }
    console.log('通过 ---空--- 校验')
    wx.showToast({
      title: '上传图片中',
      icon: 'loading',
      duration: 30000,
      mask: true
    })
    this.OnUpImg()
  },
  OnUpImg: function () {
    let promiseArr = []
    let fileIds = []     // 将图片的fileId存放到一个数组中
    let imgLength = this.data.imgOne.length;
    // 图片上传
    for (let i = 0; i < imgLength; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.imgOne[i]
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({    
          cloudPath: 'testdir/' + Date.now() + '-' + Math.random() * 1000000 + suffix, 
          filePath: item,
          success: (res) => {
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    }
    Promise.all(promiseArr)
      .then((res) => {
        // 跳转到我的店铺
        wx.navigateTo({
          url: '../myshop/myshop'
        })
        // 上传店铺信息
        this.addStore()
        this.addtoDB(fileIds)
      })
      .catch((err) => {
        console.error(err)       // 上传图片失败
        wx.showToast({
          title: '上传失败 请再次点击发布',
          icon: 'none',
          duration: 3000
        })
      })
  },
  addtoDB: function (fileIds) {
    wx.showToast({
      title: '注册成功',
    })
  },
  // 选择图片 + 回显 
  onChooseOne: function () {
    let that = this
    wx.chooseImage({
      count: this.data.MAXCOUNTIMAGE - this.data.imgOne.length,
      // sizeType: ['compressed','original'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      // sourceType: ['album'],
      success(res) {
        console.log(res)
        let tempArr = that.data.imgOne.concat(res.tempFilePaths)
        that.setData({
          'imgOne': tempArr
        })
        if (that.data.imgOne.length >= that.data.MAXCOUNTIMAGE) {
          that.setData({
            imgOneSwitch: false
          })
        }
      }
    })
  },
  // 删除图片功能
  reBackImg: function (e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    console.log(index)
    let arr = this.data.imgOne
    arr.splice(index, 1)
    if (arr.length < this.data.MAXCOUNTIMAGE && this.data.imgOneSwitch === false) {
      this.setData({
        imgOneSwitch: true
      })
    }
    this.setData({
      imgOne: arr
    })
  },
  // 预览图片
  previewImg: function (e) {
    console.log('放大图片')
    let index = e.currentTarget.dataset.index
    let item = this.data.imgOne[index]
    console.log(item)
    wx.previewImage({
      current: item, // 当前显示图片的http链接
      urls: this.data.imgOne // 需要预览的图片http链接列表
    })
  }
})
目录
相关文章
|
5月前
|
机器学习/深度学习 小程序 前端开发
微信小程序——实现对话模式(调用大模型图片生成)
微信小程序——实现对话模式(调用大模型图片生成)
321 3
|
5月前
|
小程序 容器
小程序图片水平垂直居中显示在view中
小程序图片水平垂直居中显示在view中
101 0
|
5月前
|
存储 开发框架 JavaScript
uniapp、vue、小程序、js图片转base64 示例代码
uniapp、vue、小程序、js图片转base64 示例代码
374 0
|
5月前
|
前端开发 小程序
微信小程序canvas画布绘制base64图片并保存图片到相册中
微信小程序canvas画布绘制base64图片并保存图片到相册中
169 0
|
3月前
|
小程序 开发者
【微信小程序-原生开发】实用教程05-首页(含自定义调试模式、插入图片、图文排版、底部留白、添加本地图片)
【微信小程序-原生开发】实用教程05-首页(含自定义调试模式、插入图片、图文排版、底部留白、添加本地图片)
39 0
|
14天前
|
小程序
小程序消除图片下边距的三个方法
小程序消除图片下边距的三个方法
37 11
|
2月前
|
小程序 前端开发
|
2月前
|
运维 小程序 前端开发
小程序开发问题之在小程序中调用my.chooseImage接口让用户选择图片如何解决
小程序开发问题之在小程序中调用my.chooseImage接口让用户选择图片如何解决
|
3月前
|
小程序 前端开发
【非常全】微信小程序下载图片到相册,微信小程序自动获取分享图片到相册
【非常全】微信小程序下载图片到相册,微信小程序自动获取分享图片到相册
168 3
|
3月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp小程序的图片推荐系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp小程序的图片推荐系统附带文章源码部署视频讲解等
34 0
下一篇
无影云桌面