一、上传图片和上传视频的代码整合
1.将uploadImg()和uploadVideo()整合成uploadFile()
//上传文件 uploadFile(tempFile,fileName){ //传递两个参数,tempFile是所选文件的临时路径,fileName是上传到云存储的cloudPath的值 console.log("要上传文件的临时路径",tempFile) let timestamp = (new Date()).valueOf() wx.cloud.uploadFile({ cloudPath: fileName, //云存储的路径 filePath: tempFile, // 文件路径 }).then(res => { console.log("上传成功",res) wx.showToast({ title: '上传成功', icon:"success", duration:2000 }) let that = this setTimeout(function(){ that.setData({ videoUrl:res.fileID, imageUrl:res.fileID }) },2000) }) .catch(err => { console.log("上传失败",err); }) }
二、在chooseImg()函数和chooseVideo()函数中分别调用整合后的上传文件函数uploadFile()
1.在chooseImg()函数中调用uploadFile()
chooseImg(){ let that = this wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success (res) { console.log("选择成功",res); wx.showLoading({ title: '上传中', }) // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths //调用uploadImg(tempFile)函数,实现图片上传功能 //that.uploadImg(tempFilePaths[0]) //调用uploadFile()实现上传文件功能 let timestamp = (new Date()).valueOf() that.uploadFile(tempFilePaths[0],+timestamp+'.png') //传递两个参数 } }) }
2.在chooseVideo()函数中调用uploadFile()
//第一步:选择要上传的视频 chooseVideo(){ let that = this wx.chooseVideo({ sourceType: ['album','camera'], maxDuration: 60, camera: 'back', success(res) { //console.log(res.tempFilePath); console.log("----------",res.tempFilePath); wx.showLoading({ title: '上传中', }) //调用uploadImg(tempFile)函数,实现图片上传功能 //that.uploadVideo(res.tempFilePath) //调用uploadFile()实现上传文件功能 let timestamp = (new Date()).valueOf() that.uploadFile(res.tempFilePath,+timestamp+'.mp4') //传递两个参数 } }) }