600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 微信小程序实现图片上传功能

微信小程序实现图片上传功能

时间:2022-12-08 16:41:47

相关推荐

微信小程序实现图片上传功能

微信小程序实现图片上传和视频上传功能

服务器:阿里云

后端:PHP,提供上传接口

用到相关API:

wx.showActionSheet:显示操作菜单

wx.chooseImage:从本地相册选择图片或使用相机拍照,该api后期官方不维护,可使用 wx.chooseMedia api

wx.chooseVideo:拍摄视频或从手机相册中选视频

wx.chooseMedia:拍摄或从手机相册中选择图片或视频,官方提示:此接口不再更新,建议使用 wx.chooseMedia

选择需要上传的文件:

//可以选择视频或者图片uploadFiles(){var _this = this;wx.showActionSheet({itemList: ['选择图片', '选择视频'],success: function (res) {let xindex = res.tapIndex;if (xindex == 0){// 选择图片_this.chooseImage()} else if (xindex == 1){// 选择视频_this.chooseVideo()}},fail: function (res) {console.log(res.errMsg)}})},

选择图片或拍照

// 选择图片类型chooseImage(){wx.chooseImage({count: 1,//上传数量sizeType: ['original', 'compressed'],//图片:原图和压缩sourceType: ['album', 'camera'], // 选择图片的来源success: (res) => {let arr = res.tempFiles;var imgInfo = {};arr.map(function(v,i){v['progress'] = 0;imgInfo=v})_this.upImgs(imgInfo,'image')}})},

选择视频或拍摄

chooseVideo(){let _this=thiswx.chooseVideo({count: 1,//上传数量maxDuration:"30",//拍摄时长sizeType: ['original', 'compressed'],//图片:原图和压缩sourceType: ['album', 'camera'], // 选择图片的来源// sourceType:"album",compressed:true,camera: 'back',success: (res) => {let videoInfo = {};videoInfo['tempFilePath'] = res.tempFilePath;//路径videoInfo['size'] = res.size;// 大小videoInfo['height'] = res.height;videoInfo['width'] = res.width;videoInfo['thumbTempFilePath'] = res.thumbTempFilePath;//封面videoInfo['progress'] = 0;_this.upImgs(videoInfo,'video')}})},

上传服务器

upImgs(dataInfo, type) {let that=thiswx.showLoading({title: '上传中',mask:true,})wx.uploadFile({url: '上传的网络地址',filePath: type=='video'?dataInfo.tempFilePath:dataInfo.path,formData:null,name: 'file',header: {'content-type': 'multipart/form-data'},success:(res=>{wx.hideLoading()//判断上传的是图片还是视频if(type=="video"){that.setData({console.log('视频地址:'+data.data.src)console.log('视频封面:'+data.data.src+'?spm=qipa250&x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_400,m_fast')}else{console.log('图片地址:'+ data.data.src)}})})},

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。