小程序上传/编辑图片

简介: 小程序上传/编辑图片

查了很多资料,自己写的,功能实现了,但是代码比较冗余。第一次写小程序,不太了解商品上传这里的思路。我是先把图片上传到云存储,然后把云存储的图片地址和其他商品信息一起传到云数据库的。轮播图和详情图分开上传,写了两次上传图片,编辑功能很麻烦也是,大家有什么好的方法吗?交流一下。

// pages/main/shopping/shopping.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    newAddLbt:[],       // 编辑时新增轮播图列表
    newAddXqt:[],       // 编辑时新增详情图列表
    lbbd: true,         // 编辑时轮播图点击选择图片标的
    xqbd: true,         // 编辑时详情图点击选择图片标的
    imageList: [],      // 轮播图列表 
    xqList: [],         // 详情图列表
    shopTitle: '',      // 商品标题
    shopIntroduce: '',  // 商品介绍
    shopPrice: '',      // 商品价格
    integral: '',       // 积分
    shopStock: '',      // 库存
    postage: '',        // 邮费
    imgOneSwitch: true,
    imgTwoSwitch: true,
    imgOne: [],         // 发布商品轮播图片
    imgTwo: [],         // 发布商品详情图片
    exitLbtList: [],    // 修改上传图片的临时链接列表 轮播图
    exitxqList: [],     // 修改上传图片的临时链接列表 详情图
    MAXCOUNTIMAGE: 6,
    detailsData: {},    // 详情页数据
    _id: ''             // 被编辑商品的id
  },
  getShopTitle(e){
    this.data.shopTitle = e.detail
  },
  getShopIntroduce(e){
    this.data.shopIntroduce = e.detail
  },
  getShopStock(e){
    this.data.shopStock = e.detail
  },
  getShopPostage(e){
    this.data.postage = e.detail
  },
  getShopPrice(e){
    this.data.shopPrice = e.detail
  },
  getIntegral(e){
    this.data.integral = e.detail
  },
  // 轮播图选择图片 + 回显 
  onChooseOne: function () {
    let that = this
    wx.chooseImage({
      count: this.data.MAXCOUNTIMAGE - this.data.imgOne.length,
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      success(res) {
        if(that.data._id){
          // 修改
          let tempArr = that.data.exitLbtList.concat(res.tempFilePaths)
          let newArr =  that.data.imgOne.concat(res.tempFilePaths)
          that.setData({
            'exitLbtList': tempArr,
            'imgOne': newArr
          })
          console.log(that.data.exitLbtList);
        } else {
          // 添加
          let tempArr = that.data.imgOne.concat(res.tempFilePaths)
          // 将零时链接保存在imgOne
          that.setData({
            'imgOne': tempArr
          })
        }
        // 将轮播图保存到云存储
        that.onSave()
        if (that.data.imgOne.length >= that.data.MAXCOUNTIMAGE) {
          that.setData({
            imgOneSwitch: false
          })
        }
      }
    })
  },
  // 轮播图保存到 存储 & 数据库的提示
  onSave: function () {
    if (this.data.imgOne.length == 0) {
      wx.showToast({
        title: '请添加图片',
        icon: 'none'
      })
      return
    }
    console.log('通过 ---空--- 校验')
    this.OnUpImg() // 上传到云存储
  },
  // 将轮播图上传到云存储
  OnUpImg: function () {
    let promiseArr = []
    let fileIds = []     // 将图片的fileId存放到一个数组中
    if(this.data._id) {
      // 修改
      var imgLength = this.data.exitLbtList.length;
    } else {
      // 添加
      var imgLength = this.data.imgOne.length;
    }
    // 图片上传
    for (let i = 0; i < imgLength; i++) {
      let p = new Promise((resolve, reject) => {
        if(this.data._id) {
          // 修改
          var item = this.data.exitLbtList[i]
        } else {
          // 添加
          var item = this.data.imgOne[i]
        }
        let suffix = /\.\w+$/.exec(item)[0]     
        wx.cloud.uploadFile({    
          cloudPath: 'carouselMap/' + Date.now() + '-' + Math.random() * 1000000 + suffix, 
          filePath: item,
          success: (res) => {
            fileIds = fileIds.concat(res.fileID)       // 拼接   
            if(this.data._id) {
              // 修改
              var onePic = this.data.imgOne // 编辑-原本已经上传到云存储的图片列表
              fileIds.push(...onePic)
              let newArr = []
              fileIds.forEach(item => {
                if(!item.startsWith("http")){
                  newArr.push(item)
                }
              })
              // 去重
              newArr = [...new Set(newArr)]
              // imageList 传云数据库的图片url集合
              this.setData({
                imageList: newArr,
                newAddLbt: newArr,
                lbbd: false
              })
              console.log(this.data.imageList);
            } else {
              // 添加
              this.setData({
                imageList: fileIds
              })
            }
            console.log(this.data.imageList); // 2次
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    }
    Promise.all(promiseArr)
      .then((res) => {
        console.log('轮播图上传到云存储成功');
      })
      .catch((err) => {
        console.error(err)       // 上传图片失败
        wx.showToast({
          title: '上传失败 请再次点击发布',
          icon: 'none',
          duration: 3000
        })
      })
  },
  // 详情图选择图片 + 回显 
  onChooseTwo: function () {
    let that = this
    wx.chooseImage({
      count: this.data.MAXCOUNTIMAGE - this.data.imgTwo.length,
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      success(res) {
        if(that.data._id){
          // 修改
          let tempArr = that.data.exitxqList.concat(res.tempFilePaths)
          let newArrTwo =  that.data.imgTwo.concat(res.tempFilePaths)
          that.setData({
            'exitxqList': tempArr,
            'imgTwo': newArrTwo
          })
          console.log(that.data.exitxqList);
        } else {
          // 添加
          let tempArr = that.data.imgTwo.concat(res.tempFilePaths)
          // 将临时链接保存在imgTwo
          that.setData({
            'imgTwo': tempArr
          })
        }
        // 将详情图保存到云存储
        that.onSaveTwo()
        if (that.data.imgTwo.length >= that.data.MAXCOUNTIMAGE) {
          that.setData({
            imgTwoSwitch: false
          })
        }
      }
    })
  },
  // 将详情图保存到 存储 & 数据库的提示
  onSaveTwo: function () {
    if (this.data.imgTwo.length == 0) {
      wx.showToast({
        title: '请添加图片',
        icon: 'none'
      })
      return
    }
    this.OnUpImgTwo()
  },
  // 将详情图上传到云存储
  OnUpImgTwo: function () {
    let promiseArr = []
    let fileIds = []     // 将图片的fileId存放到一个数组中
    if(this.data._id) {
      // 修改
      var imgLength = this.data.exitxqList.length;
    } else {
      // 添加
      var imgLength = this.data.imgTwo.length;
    }
    // 图片上传
    for (let i = 0; i < imgLength; i++) {
      let p = new Promise((resolve, reject) => {
        if(this.data._id) {
          // 修改
          var item = this.data.exitxqList[i]
        } else {
          // 添加
          var item = this.data.imgTwo[i]
        }
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({    
          cloudPath: 'detailsMap/' + Date.now() + '-' + Math.random() * 1000000 + suffix, 
          filePath: item,
          success: (res) => {
            fileIds = fileIds.concat(res.fileID)       // 拼接   
            if(this.data._id) {
              // 修改
              var twoPic = this.data.imgTwo // 编辑-原本已经上传到云存储的图片列表
              fileIds.push(...twoPic)
              let newArr1 = []
              fileIds.forEach(item => {
                if(!item.startsWith("http")){
                  newArr1.push(item)
                }
              })
              // 去重
              newArr1 = [...new Set(newArr1)]
              this.setData({
                xqList: newArr1,
                newAddXqt: newArr1,
                xqbd: false
              })
            } else {
              // 添加
              this.setData({
                xqList: fileIds
              }) 
            }
            console.log(this.data.xqList);  // 2次
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    }
    Promise.all(promiseArr)
      .then((res) => {
        console.log('详情图上传到云存储成功');
      })
      .catch((err) => {
        console.error(err)       // 上传图片失败
        wx.showToast({
          title: '上传失败 请再次点击发布',
          icon: 'none',
          duration: 3000
        })
      })
  },
  // 点击发布商品
  releaseshop(){
    this.addshops()    // 调用添加商品方法,将商品所有数据传入云数据库
  },
  dataFun(){
    if (this.data.lbbd === false && this.data.xqbd === true) {
      // 如果编辑时点击了选择轮播图
      var arr = this.data.imgTwo
      var arr1 = []
      arr.forEach(item => {
        console.log(item);
        if(item.indexOf('wxfile') === -1) {
          arr1.push(item)
        }
      })
      this.setData({
        xqList: [...new Set(arr1)]
      })
    } else if(this.data.xqbd === false && this.data.lbbd === true) {
      var arr = this.data.imgOne
      var arr2 = []
      arr.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arr2.push(item)
        }
      })
      // 如果编辑时点击了选择详情图
      this.setData({
        imageList: [...new Set(arr2)]
      })
    } 
    else if(this.data.xqbd === false && this.data.lbbd === false) {
      var arr = this.data.newAddLbt;
      var arrn = []
      var arr2 = this.data.newAddXqt
      var arrnn = []
      arr.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arrn.push(item)
        }
      })
      arr2.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arrnn.push(item)
        }
      })
      // 如果编辑时轮播图和详情图都点击了
      this.setData({
        imageList: [...new Set(arrn)],
        xqList: [...new Set(arrnn)]
      })
    } 
    else if (this.data.xqbd === true && this.data.lbbd === true) {
      var arr = this.data.imgTwo
      var arr1 = []
      arr.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arr1.push(item)
        }
      })
      var arr = this.data.imgOne
      var arr2 = []
      arr.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arr2.push(item)
        }
      })
      // 如果编辑时都没点击
      this.setData({
        imageList: [...new Set(arr2)],
        xqList: [...new Set(arr1)]
      })
    }
  },
  // 将商品添加到云数据库
  addshops(){
    if(this.data._id){
      this.dataFun()
      // 去掉wxfile图片文件
      let arr = this.data.imageList;
      var arr1 = []
      arr.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arr1.push(item)
        }
      })
      let arrr = this.data.xqList;
      var arr2 = []
      arrr.forEach(item => {
        if(item.indexOf('wxfile') === -1) {
          arr2.push(item)
        }
      })
      // 修改商品
      wx.cloud.database().collection('releaseProduct')
      .doc(this.data._id)
      .update({
        data: {
          shopTitle: this.data.shopTitle,
          shopIntroduce: this.data.shopIntroduce,
          shopPrice: this.data.shopPrice,
          shopStock: this.data.shopStock,
          postage: this.data.postage,
          integral: this.data.integral,
          lbtImg: arr1,
          xqList: arr2
        }
      }).then(res => {
        console.log('修改成功',res);
        //  跳转到我的店铺
        wx.navigateTo({
          url: '../myshop/myshop'
        })
        // 修改成功提示的方法
        wx.showToast({
          title: '修改成功',
        })
      }).catch(err => {
        wx.showToast({
          title: '修改失败',
          icon: 'none',
          duration: 3000
        })
      })
    } else {
      // 添加数据
      wx.cloud.database().collection('releaseProduct')
      .add({
        data: {
          shopTitle: this.data.shopTitle,
          shopIntroduce: this.data.shopIntroduce,
          shopPrice: this.data.shopPrice,
          shopStock: this.data.shopStock,
          postage: this.data.postage,
          integral: this.data.integral,
          lbtImg: this.data.imageList,
          xqList: this.data.xqList
        }
      }).then(res => {
        //  跳转到我的店铺
        wx.navigateTo({
          url: '../myshop/myshop'
        })
        // 发布成功提示的方法
        wx.showToast({
          title: '发布成功',
        })
      }).catch(err => {
        wx.showToast({
          title: '发布失败',
          icon: 'none',
          duration: 3000
        })
      })
    }
  },
  // 轮播图删除图片功能
  reBackImg: function (e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    console.log(index)
    let arr = this.data.imgOne
    let arr1 = this.data.imageList
    if(this.data._id) {
      // 修改时点击删除
      arr1.splice(index,1)
      arr.splice(index, 1)
    } else {
      // 添加时点击删除
      arr.splice(index, 1)
    }
    // 编辑时删除已经上传云存储的图片
    wx.cloud.deleteFile({
      fileList: [e.currentTarget.dataset.main],
      success(res){
        console.log(res,'删除文件11111')
      },
      fail(err){
        console.log(err)
      }
    })
    // 添加图片icon是否显示
    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链接列表
    })
  },
  // 删除图片功能
  reBackImgTwo: function (e) {
    console.log(e.currentTarget.dataset.main);
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    console.log(index)
    let arr = this.data.imgTwo
    let arr2 = this.data.xqList
    if(this.data._id) {
      // 修改时点击删除
      arr2.splice(index,1)
      arr.splice(index, 1)
    } else {
      // 添加时点击删除
      arr.splice(index, 1)
    }
    // 编辑/添加时删除已经上传云存储的图片
    wx.cloud.deleteFile({
      fileList: [e.currentTarget.dataset.main],
      success(res){
        console.log(res,'删除文件11111')
      },
      fail(err){
        console.log(err)
      }
    })
    if (arr.length < this.data.MAXCOUNTIMAGE && this.data.imgTwoSwitch === false) {
      this.setData({
        imgTwoSwitch: true
      })
    }
    this.setData({
      imgTwo: arr
    })
  },
  // 预览图片
  previewImgTwo: function (e) {
    console.log('放大图片')
    let index = e.currentTarget.dataset.index
    let item = this.data.imgTwo[index]
    console.log(item)
    wx.previewImage({
      current: item, // 当前显示图片的http链接
      urls: this.data.imgTwo // 需要预览的图片http链接列表
    })
  },
  onLoad: function (options) {
    if(!options.queryBean) {
      return false
    }
    var queryBean = JSON.parse(options.queryBean)
    // detailsData: queryBean
    this.setData({
      integral: queryBean.integral,
      shopTitle: queryBean.shopTitle,
      shopIntroduce: queryBean.shopIntroduce,
      shopStock: queryBean.shopStock,
      shopPrice: queryBean.shopPrice,
      postage: queryBean.postage,
      imgOne: queryBean.lbtImg,
      imgTwo: queryBean.xqList,
      _id: queryBean._id
    })
    console.log(this.data.detailsData);
  }
})
目录
相关文章
|
2月前
|
机器学习/深度学习 小程序 前端开发
微信小程序——实现对话模式(调用大模型图片生成)
微信小程序——实现对话模式(调用大模型图片生成)
191 3
|
2月前
|
小程序 容器
小程序图片水平垂直居中显示在view中
小程序图片水平垂直居中显示在view中
|
2月前
|
存储 开发框架 JavaScript
uniapp、vue、小程序、js图片转base64 示例代码
uniapp、vue、小程序、js图片转base64 示例代码
111 0
|
2月前
|
前端开发 小程序
微信小程序canvas画布绘制base64图片并保存图片到相册中
微信小程序canvas画布绘制base64图片并保存图片到相册中
125 0
|
2月前
|
小程序 前端开发
解决小程序 scroll-view 里面的image有间距、小程序里面的图片之间有空隙的问题。
解决小程序 scroll-view 里面的image有间距、小程序里面的图片之间有空隙的问题。
|
3天前
|
小程序 开发者
【微信小程序-原生开发】实用教程05-首页(含自定义调试模式、插入图片、图文排版、底部留白、添加本地图片)
【微信小程序-原生开发】实用教程05-首页(含自定义调试模式、插入图片、图文排版、底部留白、添加本地图片)
11 0
|
5天前
|
小程序 前端开发
【非常全】微信小程序下载图片到相册,微信小程序自动获取分享图片到相册
【非常全】微信小程序下载图片到相册,微信小程序自动获取分享图片到相册
19 3
|
3天前
|
前端开发 小程序
【微信小程序-原生开发】实用教程20 - 生成海报(实战范例为生成活动海报,内含生成指定页面的小程序二维码,保存图片到手机,canvas 系列教程)
【微信小程序-原生开发】实用教程20 - 生成海报(实战范例为生成活动海报,内含生成指定页面的小程序二维码,保存图片到手机,canvas 系列教程)
6 0
|
3天前
|
小程序 JavaScript 前端开发
【微信小程序-原生开发】实用教程06-轮播图、分类页签 tab 、成员列表(含Tdesign升级,切换调试基础库,设置全局样式,配置组件按需注入,添加图片素材,wx:for,生命周期 onLoad)
【微信小程序-原生开发】实用教程06-轮播图、分类页签 tab 、成员列表(含Tdesign升级,切换调试基础库,设置全局样式,配置组件按需注入,添加图片素材,wx:for,生命周期 onLoad)
6 0
|
10天前
|
小程序 API
技术心得记录:微信小程序之图片频繁变化,几秒之后输出结果(适用于抽奖)
技术心得记录:微信小程序之图片频繁变化,几秒之后输出结果(适用于抽奖)
10 0