说明 图片/视频这类文件是从客户端会话选择文件。
一、wxml文件添加if切换显示
<!--上传文件到云存储--> <button bindtap="chooseImg" type="primary" >上传单张图片</button> <button bindtap="chooseVideo" type="primary" >上传单个视频</button> <view class="myFile"> <image wx:if="{{showImage}}" src="{{imageUrl}}"></image> <video wx:if="{{showVideo}}" src="{{videoUrl}}"></video> </view>
二、wxss文件
.myFile{ margin: 30rpx auto; text-align: center; } button{ margin: 30rpx; }
三、js文件
1、定义data
初始值赋值,定义图片和视频初始的显示状态(都隐藏不显示)
data:{ //默认图片和视频都不显示 showImage:false, showVideo:false },
2、上传图片和上传视频的代码整合
将uploadImg()和uploadVideo()整合成uploadFile()
uploadFile(tempFile,fileName,type){ //传递三个参数,tempFile是所选文件的临时路径,fileName是上传到云存储的cloudPath的值,type表示上传的文件类型(1表示上传图片,2表示上传视频) 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 if(type==1){ setTimeout(function(){ that.setData({ imageUrl:res.fileID, showImage:true, //显示图片 showVideo:false //隐藏视频 }) },2000) }else if(type ==2){ setTimeout(function(){ that.setData({ videoUrl:res.fileID, showImage:false, showVideo:true }) },2000) } }) .catch(err => { console.log("上传失败",err); }) }
3、在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',1) //传递三个参数 } }) }
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',2) //传递三个参数(第一个参数传递所选文件的临时路径,第二个参数传递云存储的路径,第三个参数传递上传文件的类型) } }) }
四、最终效果