uni-app H5上传图片压缩体积大小

发布于:2024-05-07 ⋅ 阅读:(32) ⋅ 点赞:(0)

           // 用户上传头像
            uploadAvatar(){
                let _this = this
                uni.chooseImage({
                    success: (chooseImageRes) => {
                        const tempFilePaths = chooseImageRes.tempFilePaths;
                        let filePath = tempFilePaths[0]
                        //#ifdef APP-IOS || APP-ANDROID
                            const theme = uni.getStorageSync('theme');
                            let color = theme == 'purple' ? "#000000" : "#ffffff"
                            let style = theme == 'purple' ? "black" : "white"
                            var styles = {
                                color: color,
                                background: "rgba(0,0,0,0.0)",
                                style: style,
                            }
                            var waiting = plus.nativeUI.showWaiting("上传中...", styles);
                            _this.uploadFile(filePath)
                        //#endif
                        // #ifndef APP-IOS || APP-ANDROID
                            uni.showLoading({
                                title: '上传中...'
                            });
                            _this.afterRead(tempFilePaths)
                        // #endif
                    }
                });
            },
            //压缩
            recursionCompressH5(url) {
              console.log("url",url)
                 return new Promise((resolve, reject) => {
                      this.recursionCompress(url,resolve)
                 })
            },
            // 传入blob路径,.then()获取blob文件
            httpRequest(src) {
                let that = this
                return new Promise((resolve, reject) => {
                  let xhr = new XMLHttpRequest()
                  xhr.open('GET', src, true)
                  xhr.responseType = 'blob'
                  xhr.onload = function (e) {
                      if (this.status == 200) {
                         let myBlob = this.response
                         let files = new window.File(
                            [myBlob],
                            myBlob.type,
                            { type: myBlob.type }
                         ) // myBlob.type 自定义文件名
                            resolve(files)
                         } else {
                            reject(false)
                         }
                      }
                  xhr.send()
                })
            }, 
            recursionCompress(url,resolve) {
                let _this = this
                  uni.getImageInfo({
                      src: url,
                      success(res) {
                          let canvasWidth = res.width; //图片原始长宽
                          let canvasHeight = res.height;
                          let img = new Image();
                        console.log(res,'resinfo')
                          img.src = res.path;
                          let canvas = document.createElement("canvas");
                          let ctx = canvas.getContext("2d");
                          canvas.width = canvasWidth / 2;
                          canvas.height = canvasHeight / 2;
                          ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
                          canvas.toBlob(function(fileSrc) {
                              let imgSrc = window.URL.createObjectURL(fileSrc);
                              uni.getFileInfo({
                                  filePath: imgSrc,
                                  success: (resFileInfo) => {
                                      console.log(imgSrc, 'resFileInfo',resFileInfo)
                                      if (resFileInfo.size > 1024 * 1024) {   
                                          //压缩后大于1M就继续压缩
                                        console.log('再次压缩')
                                          _this.recursionCompress(imgSrc,resolve);
                                          // indexObj.recursionCompressH5(imgSrc, callback, item);
                                          return;
                                      } else {
                                          resolve(imgSrc)
                                      }
                                  },
                              });
                          });
                      }
                  });
            },
            afterRead(e) {
              let _this = this
              const file = e
              console.log("e",e)
              // 遍历图片资源
              file.map(item => {
              console.log(item,'item')
              // 进行压缩图片
              this.recursionCompressH5(item).then(url =>{
                  console.log(url,'url')
                  _this.httpRequest(url).then(res => {
                              console.log(res,'成功转换为blob文件');
                            const fileReader = new FileReader()
                              fileReader.readAsDataURL(res) // 读取blob类型的图像文件(不是blob路径),读取成功触发onload方法,并得到result(base64格式的图片)
                              fileReader.onload = (event) => {
                                console.log(fileReader.result,'fileReader.result - base64格式');
                                if (fileReader.result) {
                                    // 上传最终压缩之后的图片
                                    _this.uploadFile(fileReader.result).then(res => {
                                        // uni.hideLoading();
                                        console.log(res)
                                        // this.fileList.push(res)
                                    }).catch(() => {
                                        //#ifdef APP-PLUS
                                        plus.nativeUI.closeWaiting();
                                        //#endif
                                        uni.hideLoading();
                                    })
                                  // 调用wx_uploadImage接口,图片大小必须是1M以下,否则报错
                                  // wx_uploadImage({
                                  //   image: fileReader.result
                                  // }).then(res => {
                                  //   console.log('上传图片成功', res)
                                  //   this.image = res.storage_path
                                  // })
                                }
                              }
                          })
                    })
              })
            },
            uploadFile(path){
                let _this = this
                let url = apiBaseUrl+'mfh/updateHead/'+_this.info.uid
                let token = this.$db.get("userToken");
                const uploadTask = uni.uploadFile({
                    url:url,
                    filePath: path,
                    fileType: 'image',
                    name: 'file',
                    header: {
                        // 'Content-Type': 'multipart/form-data',
                        'Authorization': 'Bearer ' + token
                    },
                    success: (res) => {
                        console.log('完成'+JSON.stringify(res))
                        let data = JSON.parse(res.data);
                        if(data.status){
                            _this.$common.successToShow('头像上传完成')
                            _this.requestUserInfo()
                        }else{
                            if (data.message) {
                                _this.$common.errorToShow(data.message)
                            }
                        }
                    },
                    fail: (error) => {
                        if (error && error.message) {
                            _this.$common.errorToShow(res.message)
                        }
                        //#ifdef APP-PLUS
                        plus.nativeUI.closeWaiting();
                        //#endif
                        uni.hideLoading();
                    },
                    complete: () => {
                        //#ifdef APP-PLUS
                        plus.nativeUI.closeWaiting();
                        //#endif
                        uni.hideLoading();
                    }
                });
            },