">
美文网首页
微信小程序配合vant压缩图片上传

微信小程序配合vant压缩图片上传

作者: 海豚先生的博客 | 来源:发表于2023-06-29 15:11 被阅读0次

    使用vant 组件 <van-uploader bind:after-read="afterRead" />

        afterRead(event: any) {
          console.log(event.detail);
          const { file } = event.detail;
          console.log(111, file.size / 1024 / 1024);
          const maxSize = file.size / 1024 / 1024;
          let url = file.url;
          const _this = this
          const getImgInfo = (url, resolve) => {
            wx.getImageInfo({
              src: url,
              success(res) {
                console.log('imginfo', res);
                const { width, height } = res;
                wx.compressImage({
                  src: url,
                  quality: 1,
                  compressedWidth: width,
                  compressedHeight: height,
                  success(res) {
                    console.log('comporess', res);
                    url = res.tempFilePath;
                    // wx.saveImageToPhotosAlbum({
                    //   filePath: res.tempFilePath,
                    // })
                    resolve(url);
                  }
                })
              }
            })
          };
          new Promise((resolve) => {
            if (maxSize > 5) {
              getImgInfo(url, resolve);
              return;
            }
            resolve(url);
          }).then(filePath => {
            console.log('then', filePath);
            const token = wx.getStorageSync('token');
            const host = getApp().globalData.host
            wx.showLoading({ title: '加载中' });
            wx.uploadFile({
              url: `${host}/api/v1/weixin/common/upload`,
              header: { 'Authorization': token },
              filePath,
              name: 'file',
              success(res) {
                const { data, code, msg } = JSON.parse(res.data);
                if (code != 0) {
                  wx.showToast({
                    icon: 'none',
                    title: msg || '网络错误,请返回重试',
                  })
                  wx.hideLoading();
                  return
                }
                wx.hideLoading();
                const { list } = _this.data;
                const fileInfo = { ...file, ...data }
                _this.setData(
                  { list: [...list, fileInfo] },
                  () => {
                    const fileNos = [...list, fileInfo].map(i => i.fileNo)
                    _this.triggerEvent('setFileList', { files: fileNos })
                  })
              },
            });
          })
        },
    

    相关文章

      网友评论

          本文标题:微信小程序配合vant压缩图片上传

          本文链接:https://www.haomeiwen.com/subject/qhaaydtx.html