小程序上传/编辑图片

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

// 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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值