大家好,我是小兔僧。九宫格@toc1中删除图片和显示图片的功能,实现效果,废话不多说,先看看效果:说明:中间的停顿是我选择上传照片的时候。点击右上角的“x”删除图片,点击“下载第一张图片”按钮下载并打开第一张图片,因为我传入的download()函数是云存储的图片地址的第一张照片。2.JavaScript代码首先我们需要在页面的数据对象中定义两个数组fileList和linshi/***页面初始数据*/data:{fileList:[],//图片数组linshi带图片addressstored:[],//存放选中图片的临时数组},里面有很详细的代码注释,通俗易懂,很简单。这是上传图片功能的代码//上传图片uploadToCloud(){letthat=this;wx.chooseImage({count:9,//count属性决定最多可以上传9张图片,下面的属性可以在官方说明中找到,就不一一解释了sizeType:['original','compressed'],sourceType:['album','camera'],success(res){wx.showLoading({title:'Uploading',})console.log(res)//给linshi临时数组赋值andstoreittemporarythat.setData({linshi:that.data.linshi.concat(res.tempFilePaths)})console.log(that.data.linshi)//设置图片存储在云存储位置和图片名称letlujin="img/"+newDate().getTime()+"-"+Math.floor(Math.random()*1000);//这里调用了图片上传函数wx.cloud.uploadFile()//传给wx.cloud.uploadFile的cloudPath属性的值不能重复!!!巨大的坑,加个索引可以避免重复constuploadTasks=that.data.linshi.map((item,index)=>that.uploadFilePromise(index+lujin,item));//promise.all方法会等待在继续执行之前要完成的map方法n方法中的代码Promise.all(uploadTasks).then(data=>{console.log(data)wx.hideLoading()wx.showToast({title:'上传成功',icon:'none'});constnewFileList=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:'上传失败”,图标:“无”});console.log(e);});}})},//上传到云存储,获取图片地址uploadFilePromise(fileName,chooseResult){returnwx.cloud.uploadFile({cloudPath:文件名,文件路径:选择结果});},下面是删除函数://删除图片delete:function(event){letthat=this;console.log(event)letinde=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函数的事件是用来接收我们在wxml中绑定的id的,而id的值等于图片数组的下标索引,用来区分删除哪张图片。预览也是同样的逻辑。previewImage函数的事件是用来接收我们在wxmlurl中绑定的事件,url的值等于图片地址url,用来区分预览哪张图片,将值传给wx。由相应函数的事件参数接收。很简单的!我们在wxml中这样绑定数据,如下图:id和url可以自定义,绑定数据固定格式为data-xxx下面是下载函数://下载图片download:function(){leturl=this.data.fileList[0].url;//下载文件wx.cloud.downloadFile({fileID:url,success:res=>{console.log("文件下载成功",res);//打开文件constfilePath=res.tempFilePathwx.showModal({title:'提示',content:'下载成功,请打开另存为',showCancel:false,confirmText:'去另存为',success(res){if(res.confirm){console.log('User单击确定')wx.openDocument({filePath:filePath,success:function(re){console.log('文件打开成功',re)}})}elseif(res.cancel){console.log('User点击取消')}}})}})},使用wx.cloud.downloadFile官方方法下载,因为本例我下载的是第一张图片,所以我们传入的fileID就是图片切片数组中第一个图片的地址下载成功后,我们就可以使用wx.openDocument官方的方法打开刚才下载的图片了。非常简单易懂!3.wxml代码
