1. 程式人生 > 其它 >uniapp上傳壓縮圖片和視訊

uniapp上傳壓縮圖片和視訊

業務場景:可以上傳拍攝圖片或視訊,也可以上傳相簿圖片或視訊,圖片大於1M需要壓縮,視訊大於10M也要壓縮

介紹使用到的方法:

  1.uni.showActionSheet

  2.

            

首先選擇上傳的型別

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: () => {}   // 不論成功失敗,都執行
                    })
                }            
            }