uniapp文件上传压缩兼容H5和app端

文章讲述了在Vue项目中使用`u-upload`组件实现文件上传,包括图片压缩功能,使用Promise和async/await处理上传过程,并展示了如何将Base64转换为File对象进行上传。
摘要由CSDN通过智能技术生成

多说不宜 直接上代码

 <u-upload
              @on-choose-complete="afterRead"
              :mutiple="false"
              upload-text="上传照片"
              :size-type="sizeType"
              @on-remove="remove"
              :preview-full-image="false"
              :file-list="fileList"
              imageMode="aspectFit"
              :show-progress="false"
              width="150rpx"
              height="150rpx"
              ref="uUpload"
              :auto-upload="false"
              max-count="9"
              :name="'img'"
            >
            </u-upload>
async uploadFilePromise(url) {
      console.log(url,'所有文件')
      let uploadUrl = "";
      await url.map((item) => {
        /*#ifdef APP-PLUS*/
        uni.compressImage({
          src: item.path,
          quality: 30, //图片压缩质量,0~100,默认80,仅对jpg有效
          success: (res) => {
            uploadUrl = res;
            this.uploadFile(uploadUrl)
            //uni.getFileSystemManager() 获取全局唯一的文件管理器
            // readFile读取文件,可转换编码格式
          },
        });
        /*#endif*/
        /*#ifdef H5*/
        this.getImageInfo(item.path);
        console.log(111);
        /*#endif*/
      });
      console.log(this.uploadList,'上传后的文件')
    },
     async afterRead(event) {
      console.log(event);
      let lists = [];
      await event.map((photo) => {
        lists.push(photo.file);
      });
      console.log(lists,'文件目录')
      let fileListLen = this[`fileList`].length;
      const result = await this.uploadFilePromise(lists);
      console.log(result);
      // 垃圾回收
      // window.URL.revokeObjectURL(lists[i].url);
      // console.log("上传结果", result);
    },
     uploadFile(file) {
      console.log(file);
      // return
      return new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
          url: this.action,
          filePath: file.path || file.tempFilePath,
          name: "img",
          type: "image/jpeg",
          success: (uploadFileRes) => {
            console.log(uploadFileRes)
            if (uploadFileRes.statusCode === 200) {
              const data = JSON.parse(uploadFileRes.data);
              this.uploadList.push(data);
              this.urlImg = data.path;
              uni.showToast({
                title: data.msg,
                icon: "none",
              });
            } else {
              console.log(uploadFileRes);
              uni.showToast({
                title: "上传失败",
                icon: "none",
              });
            }
          },
          fail(error) {
            // reject(false)
            uni.$u.toast(error.errMsg);
            console.log("图片上传失败", error);
          },
        });
      });
    },
    convertBase64UrlToFile(base64) {
      let urlData = base64.dataURL;
      let type = base64.type;
      let contentName = base64.contentName;
      let bytes = null;
      if (urlData.split(",").length > 1) {
        //是否带前缀
        bytes = window.atob(urlData.split(",")[1]); // 去掉url的头,并转换为byte
      } else {
        bytes = window.atob(urlData);
      }
      // 处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      let ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      let result = new Blob([ab], {
        type: type,
      });
      let result1 = new File([result], contentName, {
        type: type,
      });
      result1.path = window.URL.createObjectURL(result);
      return result1;
    },
    async getImageInfo(src) {
      let _this = this;
      await uni.getImageInfo({
        src,
        success(res) {
          console.log("压缩前", res);
          let canvasWidth = res.width; //图片原始长宽
          let canvasHeight = res.height;
          let img = new Image();
          img.src = res.path;
          let canvas = document.createElement("canvas");
          let ctx = canvas.getContext("2d");
          // 这里根据要求限制图片宽高
          if (canvasWidth >= 1920) {
            canvas.width = canvasWidth * 0.5;
          } else {
            canvas.width = canvasWidth;
          }
          if (canvasHeight >= 1080) {
            canvas.height = canvasHeight * 0.5;
          } else {
            canvas.height = canvasHeight;
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          // canvas对图片进行缩放 0.3是我定义的图片质量,
          let base64 = canvas.toDataURL("image/jpeg", 0.3);
          // 将base64转换为filel流,
          let flie = _this.convertBase64UrlToFile({
            dataURL: base64,
            type: "image/jpeg",
            contentName: "",
          });
          console.log("压缩后", flie);
          _this.uploadFile(flie);
          // let imgSrc = window.URL.createObjectURL(flie)
        },
      });
    },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值