大家好,我叫小秃僧
这篇文章是解说云开发如何上传、下载、预览、删除图片,并且以九宫格展现图片的性能

@toc

1、 实现成果

废话少说,先看成果为敬:

阐明:
两头进展一下是我在抉择照片上传。点击右上角的“x”能够删除图片,点击“下载第一张图片”按钮能够下载并关上第一张图片,因为下载download()函数我传入的是第一张图片的云存储的图片地址。

2、JavaScript代码

首先,咱们要在页面的data对象外面定义fileList、linshi两个数组

     /**   * 页面的初始数据   */  data: {    fileList:[],      //寄存有图片地址的图片数组    linshi:[],   //寄存抉择的图片的长期数组  },
有很具体的代码正文,很好了解,非常简单。这是上传图片函数的代码
  // 上传图片  uploadToCloud() {        let that = this;        wx.chooseImage({          count: 9,         //count属性确定最多能够上传9张,下方属性能够看看官网的阐明,就不一一阐明          sizeType: ['original', 'compressed'],          sourceType: ['album', 'camera'],          success (res) {            wx.showLoading({              title: '正在上传',            })                console.log(res)            //赋值给linshi长期数组临时存储起来            that.setData({              linshi:that.data.linshi.concat(res.tempFilePaths)            })            console.log(that.data.linshi)            //设置图片存储到云存储的地位和图片名称            let lujin = "img/" + new Date().getTime() +"-"+ Math.floor(Math.random() * 1000);            //这里调用了图片上传函数wx.cloud.uploadFile()            //传给wx.cloud.uploadFile的cloudPath属性的值不能反复!!!巨坑,加个index就能够防止反复了            const uploadTasks = that.data.linshi.map((item, index)  =>  that.uploadFilePromise(index+lujin, item));            //promise.all办法会期待map办法都执行齐全后再继续执行then办法外面的代码             Promise.all(uploadTasks)              .then(data => {                console.log(data)                wx.hideLoading()                wx.showToast({                   title: '上传胜利',                   icon: 'none'                 });                const newFileList = data.map(item => ({ url: item.fileID,isImage: true,}));                console.log(newFileList)                //每次上传胜利后,都要清空一次长期数组,防止第二次反复上传,节约存储资源,                that.setData({                   fileList: that.data.fileList.concat(newFileList),                  linshi:[],                });                              })              .catch(e => {                wx.showToast({ title: '上传失败', icon: 'none' });                console.log(e);              });                  }        })    },      //上传到云存储,并且取得图片地址      uploadFilePromise(fileName, chooseResult) {        return wx.cloud.uploadFile({          cloudPath: fileName,          filePath: chooseResult        });      },

下方是删除函数:

    //删除图片    delete:function(event){      let that = this;      console.log(event)      let inde = event.currentTarget.dataset.id      //删除数组外面的值      that.data.fileList.splice(inde,1)      that.setData({          fileList:that.data.fileList,      })    },

下方是预览函数:

    //预览图片    previewImage:function(event){      console.log(event)      wx.previewImage({        urls: [event.currentTarget.dataset.url] // 须要预览的图片http链接列表      })        },
你会发现delete函数和previewImage函数都有个接管参数event,delete函数的event是用来接管咱们在wxml绑定的id,而id的值就等于图片数组下标index,用于区别删除哪一张图片
预览也是同样的逻辑。previewImage函数的event是用来接管咱们在wxml绑定的url,而url的值就等于图片地址url,用于区别预览哪一张图片,并传值给wx.previewImage()办法进行预览即可

点击会触发对应的函数,咱们绑定的数据就会传给对应函数的event参数接管。非常简单!

咱们在wxml是这样子绑定数据的,如下图:

id和url能够自定义哈,绑定数据的固定格局是data-xxx

下方是下载函数:

  //下载图片    download:function(){      let url = this.data.fileList[0].url;      //下载文件      wx.cloud.downloadFile({        fileID: url,        success: res => {           console.log("文件下载胜利",res);          //关上文件          const filePath = res.tempFilePath          wx.showModal({            title: '提醒',            content: '下载胜利,请关上另存',            showCancel:false,            confirmText:'返回另存',            success (res) {              if (res.confirm) {                console.log('用户点击确定')                wx.openDocument({                  filePath: filePath,                  success: function (re) {                    console.log('文件关上胜利',re)                  }                })              } else if (res.cancel) {                console.log('用户点击勾销')              }            }          })        }      })    },

应用官网给的wx.cloud.downloadFile办法进行下载,因为这个示例我下载的是图片的第一张,所以fileID咱们传入的是图片数组的第一张图片的地址。

下载胜利后,咱们能够应用官网的wx.openDocument办法去关上刚刚下载的图片。

非常简单易懂滴!

3、wxml代码

<view class="des">舒适提醒:点击加号图片能够上传图片哦</view><view class="img">  <block wx:for="{{ fileList }}" wx:key="index">    <view class="img2">       <view bindtap="delete" data-id="{{index}}">x</view>       <image bindtap="previewImage" data-url="{{item.url}}" src="{{item.url}}"></image>    </view>    </block>   <image wx:if="{{fileList.length<9}}" bindtap="uploadToCloud" style="width: 200rpx;height: 200rpx;" src="/images/jiahao.png"></image></view><button style="margin: 30rpx 0" type="primary" catchtap="download">下载第一张图片</button>

在wxml里别离绑定了delete()删除函数、previewImage()预览函数、uploadToCloud()上传函数、download()下载函数。点击会别离触发不同的函数,实现对应的性能

4、wxss代码

这个wxss是规定wxml的内容是怎么显示,就是写一些款式,比方图片的宽高要多大等等

.img{  margin-left: 5%;  width: 90%;  display: flex;   flex-direction: row;   flex-wrap: wrap;}.img2{   width: 210rpx;   height: 210rpx;}.img2 view{  color: red;  z-index: 5;  position: relative;   width: 20rpx;  height: 20rpx;  margin-top:0rpx;  margin-left: 90%;}.img2 image{  width: 190rpx;  height: 190rpx;  position: relative;  z-index: 5;}.des {  padding-left: 40rpx;  padding-top: 20rpx;  font-size: 26rpx;  color: #acacac;  letter-spacing: 2rpx;  line-height: 42rpx;}
到这里就实现了,有具体的代码正文,是不是非常简单

须要源码能够点击这里

学到的童鞋,一键三连为敬!感激不尽....哈哈哈,欢送关注小秃僧!
end
欢送关注微信公众号:小秃僧