该文章功能为主,样式为次
页面展示:
前期准备:在云开发控制台的云存储环境中创建新建img文件夹和video文件夹
.wxml
<button bindtap="chooseImg">选择图片</button>
<button bindtap="chooseVideo">选择视频</button>
<image wx:if="{{showImg}}" src="{{imgUrl}}"></image>
<video wx:if="{{showVideo}}" src="{{videoUrl}}"></video>
.js
Page({
data:{
showImg:false,
showVideo:false
},
chooseImg() {
//选择图片第一步:选择你要上传的图片
wx.chooseImage({
count: 1, //可以选择多少张图片
sizeType: ['original', 'compressed'], //所选的图片的尺寸
sourceType: ['album', 'camera'], //选择图片的来源
success: res => {
console.log(res.tempFilePaths)
this.uploadFile(res.tempFilePaths[0],'img/'+'图片.jpg',1) //图片放在云存储里的img文件夹下
}
})
},
// 上传第二步:直接上传到云存储
// type 1 代表图片 type 2 代表视频
uploadFile(tempFile,fileName,type) {
console.log("要上传文件的临时路径", tempFile)
wx.cloud.uploadFile({ //将本地资源上传至云存储空间
cloudPath: fileName, //云存储路径
filePath: tempFile //要上传文件资源的路径
})
.then(res => {
console.log('上传成功', res) //res里面有我们向要的图片或视频路径
if (type ==1){ //图片
this.setData({
imgUrl:res.fileID,
showImg:true,//显示图片
showVideo:false//隐藏视频
})
}else if(type == 2 ){//视频
this.setData({
videoUrl:res.fileID,
showImg:false,//隐藏图片
showVideo:true//显示视频
})
}
})
.catch(err => {
console.log('上传失败', err)
})
},
// 上传视频
chooseVideo(){
wx.chooseVideo({
sourceType: ['album','camera'], //从相册选择视频或者拍摄视频
maxDuration: 60, //视频时长
camera: 'back',
success : res=> {
console.log(res.tempFilePath)
this.uploadFile(res.tempFilePath,'video/'+'测试视频.mp4',2)
}
})
}
})