微信小程序实现压缩图片并以文件流的方式上传接口(纯微信小程序)

// 上传图片
  uploadImages() {
    var that = this; // 将当前页面的上下文赋值给 that 变量
    // 在某个事件处理函数中调用以下代码
    wx.chooseImage({
      count: 1, // 最多可以选择的图片数量,这里设为1
      sourceType: ['album'], // 从相册选择
      success: function (res) {
        // 选择成功后,res.tempFilePaths 是选定的图片的本地文件路径列表
        const tempFilePath = res.tempFilePaths;
        wx.compressImage({
          src: tempFilePath[0],
          quality: 80, // 设置压缩质量,范围为 0-100
          success: function (res) {
            const compressedFilePath = res.tempFilePath;
            console.log(compressedFilePath, 'compressedFilePath');
            // 压缩后的图片路径进行的后续操作
            try {
              const userinfo = wx.getStorageSync('userinfo')
              let data = compressedFilePath
              wx.uploadFile({
                // 上传接口路径
                url: 'http://localhost:8090/remote/currency/import_picture',
                filePath: data,
                name: 'file', // 上传文件对应的 key 名称
                method: 'post',
                header: {
                  'content-type': 'application/form-data',
                  'Authorization': userinfo.token
                },
                // data: data
                success: function (res) {
                  // 上传成功后的处理逻辑
                  that.setData({
                    imageSrc: JSON.parse(res.data).msg // 将选择的图片路径设置为页面数据的某个属性
                  });
                },
                fail: function (res) {
                  // 上传失败后的处理逻辑
                  console.log(res, '上传失败后的处理逻辑');
                }
              })
            } catch (e) {}

          },
          fail: function (err) {
            // 压缩失败的处理
            console.error(err);
          }
        });
      }
    });
  },

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值