微信小程序-上传压缩图片和视频
业务场景:可以上传拍摄图片或视频,也可以上传相册图片或视频,图片大于1M需要压缩,视频大于10M也要压缩
介绍使用到的方法:
1.uni.showActionSheet
2.uni.chooseImage
3.uni.getImageInfo
4.uni.uploadFile
5.uni.chooseVideo
6.uni.compressVideo
首先选择上传的类型
uni.showActionSheet({ title: '选择上传类型', itemList: ['图片', '视频'], success: res => { console.log(res); if (res.tapIndex == 0) { this.chooseImages(); } else { this.chooseVideo(); } } });
图片上传
1.图片上传
// 选择照片并上传 chooseImages(){ let that = this uni.chooseImage({ sourceType: sourceType[this.sourceTypeIndex], sizeType: this.imgSizeType[this.sizeTypeIndex], count: this.maxCount, success: (res) => { // console.log(res) res.tempFilePaths.forEach((item,index)=>{ if (this.imageList.length <= this.maxCount) { const imgSize = res.tempFiles[index] && res.tempFiles[index].size ? res.tempFiles[index].size : 0; // 上传图片大于1M进行压缩 if(imgSize/1024 > 1025){ // console.log('压缩前大小---', imgSize / 1024 / 1024 + 'M'); this.compressImage(item); }else{ let tempImage = { type: 'img', imagePath: item } that.imageList.push(tempImage) this.uploadimage(item) } }else{ uni.showToast({ //显示对话框 title: "图片和视频最多9个", duration: 500, }); } }) }, fail: (err) => { } }) },
2.大于1M压缩图片再上传(需要的data参数:imageQuality: 0.5)
// 图片压缩 compressImage(src) { let that = this uni.getImageInfo({ src, success(res) { var ratio = 2; var canvasWidth = res.width //图片原始长宽 var canvasHeight = res.height while (canvasWidth > 180 || canvasHeight > 200) { // 保证宽高在200以内 canvasWidth = Math.trunc(res.width / ratio) canvasHeight = Math.trunc(res.height / ratio) ratio++; } that.cWidth = canvasWidth that.cHeight = canvasHeight var ctx = uni.createCanvasContext('canvas') ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight) ctx.draw(false, setTimeout(() => { uni.canvasToTempFilePath({ canvasId: 'canvas', destWidth: canvasWidth, destHeight: canvasHeight, fileType: 'jpg', quality: that.imageQuality, success: function(res) { // res图片临时路径 uni.getFileInfo({ filePath: res.tempFilePath, success(ress) { // console.log(ress) // 图片大小 const imgSize = ress.size // console.log('压缩后大小---', imgSize / 1024 / 1024 + 'M'); // 压缩后的大小仍大于所设大小继续压缩 if ( imgSize/1024 > 1025) { if(that.imageQuality == 1){ uni.showToast({ icon: 'none', title: '图片太大,请重新选择' }); }else{ that.imageQuality = 1 that.compressImage(res.tempFilePath) } }else{ let tempImage = { type: 'img', imagePath: res.tempFilePath } that.imageList.push(tempImage) that.uploadimage(res.tempFilePath) } } }) }, fail: function(res) { console.log(res.errMsg) } }) }, 100)) //留一定的时间绘制canvas }, fail(err) { console.log(err.errMsg) } }) },
3.上传图片到数据库
uploadimage(item){ let that = this if(this.imageList.length != 0){ uni.uploadFile({ url: that.baseUrl + '/smartriver-safety/f/uploadFiles', filePath: item, name: 'files', header:{ 'Content-Type': 'multipart/form-data', 'Authorization': uni.getStorageSync('Authentication') }, success: (res) => { // console.log(res) let resData = JSON.parse(res.data) // console.log(resData) if(resData.code == 200){ uni.showToast({ //显示对话框 title: '上传图片成功!', icon: 'success', duration: 1000, }); if(that.reportContent.eventPic !== ''){ that.reportContent.eventPic = that.reportContent.eventPic + resData.message }else{ that.reportContent.eventPic = resData.message } }else{ uni.showToast({ //显示对话框 title: resData.message, icon: 'info', duration: 2000, }); } }, fail:(err) => { // console.log(err) }, complete: () => {} // 不论成功失败,都执行 }) } uni.showToast({ //显示对话框 title: "上传中!", icon: 'loading', duration: 2000, }); },
视频上传
1.选择视频
chooseVideo(){ let that = this uni.chooseVideo({ maxDuration: 60, //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒 camera: this.cameraList[this.cameraIndex].value, //'front'、'back',默认'back' sourceType: sourceType[this.sourceTypeIndex], compressed:false,//是否压缩所选的视频源文件,默认值为 true,需要压缩。 success: res => { // console.log(res) if (that.imageList.length <= that.maxCount) { // 大于10M压缩 console.log('压缩前大小---', res.size / 1024 /1024 + 'M'); if (res.size / 1024 > 1025 * 10) { console.log('压缩') this.videoCompress(res.tempFilePath) } else { let tempVideo = { type: 'video', imagePath: res.tempFilePath } that.imageList.push(tempVideo) that.uploadVideo(res.tempFilePath) } }else{ uni.showToast({ //显示对话框 title: "图片和视频最多9个", duration: 500, }); } } }) },
2.视频压缩,代码中超过10M开始压缩,小程序最大支持上传视频的大小是压缩后的180MB。若在微信开发者工具中运行,需要安装ffepeg,安装步骤在微信官方文档中(选择打包文件夹较大的,配置环境变量即可)
// 视频压缩 微信开发者工具需要ffepeg 在D盘 videoCompress(tempFilePath){ uni.showLoading({ title: '压缩中...' }); var that = this; uni.compressVideo({ src: tempFilePath, quality: that.videoQuality, //'low':低,'medium':中,'high':高 success: function (res){ // 压缩后的大小 大于10MB,继续压缩 console.log('压缩后大小---', res.size / 1024 /1024 + 'M'); console.log('压缩后大小---', res.size / 1024 + 'K'); if ( res.size/1024 > 1025 * 10) { console.log('再次压缩') // if(that.videoQuality == 'low'){ // uni.showToast({ // icon: 'none', // title: '视频太大,请重新选择' // }); // }else{ // that.videoQuality = 'low' that.videoCompress(res.tempFilePath) // } }else{ // console.log('压缩后大小---', res.size / 1024 / 1024 + 'M'); let tempVideo = { type: 'video', imagePath: res.tempFilePath } that.imageList.push(tempVideo) that.uploadVideo(res.tempFilePath) } }, fail: function (err) { console.log(err) uni.showToast({ title:'视频压缩失败', icon:'none' },2000) } }) },
3.上传视频
uploadVideo(item){ console.log('开始上传') uni.showLoading({ title: '上传中...' }); let that = this console.log(this.imageList) if(this.imageList.length != 0){ uni.uploadFile({ url: that.baseUrl + '/smartriver-safety/f/uploadFiles', filePath: item, name: 'files', header:{ 'Content-Type': 'multipart/form-data', 'Authorization': uni.getStorageSync('Authentication') }, success: (res) => { console.log(JSON.parse(res.data)) let resData = JSON.parse(res.data) if(resData.code == 200){ uni.hideLoading(); if(that.reportContent.eventVideo !== ''){ that.reportContent.eventVideo = that.reportContent.eventVideo + resData.message }else{ that.reportContent.eventVideo = resData.message } }else{ uni.showToast({ //显示对话框 title: resData.message, icon: 'info', duration: 2000, }); } }, fail:(err) => { // console.log(err) }, complete: () => {} // 不论成功失败,都执行 }) } }