微信小程式獲取base64頭像上傳

猝死的路上發表於2024-04-20

小程式端

onChooseAvatar(e) {
  const { avatarUrl } = e.detail;
  this.avatarUrl = avatarUrl;
  let that = this;

  uni.getFileSystemManager().readFile({
    filePath: that.avatarUrl,
    encoding: "base64",
    success(res) {
      that.base64Avatar = res.data;
      //將base64圖片上傳到伺服器
      that.uploadpic(that.base64Avatar);
    },
    fail(e) {
      that.$util.Tips({
        title: "頭像讀取失敗,請稍後再試",
        icon: "error",
      });
    },
  });
}
uploadpic(base64Str) {
  let that = this;
  uni.request({
    url: HTTP_ADMIN_URL + "/api/admin/upload/base64Image",
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data: {
      base64Str,
    },
    success: function (res) {
      uni.hideLoading();
      if (res.data.code === 400) {
        that.$util.Tips({
          title: res.data.message,
        });
      } else {
        let data = res.data;
        if (data.code === 200) {
          that.avatarUrl = data.message;
          that.$util.Tips({
            title: "頭像上傳成功",
          });
        } else {
          that.$util.Tips({
            title: "頭像上傳失敗",
          });
        }
      }
    },
    fail: function (res) {
      uni.hideLoading();
      that.$util.Tips({
        title: "上傳圖片失敗",
      });
    },
  });
}

伺服器端

@Override
public String imageBase64Upload(String base64Str) throws IOException {


//uploadUrl = bucketName+region 比如test.oss-cn-hangzhou.aliyuncs.com
// accessKey osskey
// secretKey  ossSecretKey
// storeageName bucketName
// storageRegion oss-cn-hangzhou.aliyuncs.com

    OSS ossClient = new OSSClientBuilder().build(region, accessKey, secretKey);
//解碼圖片base64
    byte[] bytesFile = Base64.decode(base64Str);
    try {
        // 建立PutObject請求。
        InputStream inputStream = new ByteArrayInputStream(bytesFile);
        String rootPath = DateUtil.nowDate(Constants.DATE_FORMAT_DATE).replace("-", "/") + "/";
        String filePath =  "wechat/head/"+rootPath (年/月日的資料夾);
        //隨機資料夾名稱
        String name =  Uuid()+".png";
        //要存到oss哪個路徑,什麼名稱
        String fileName = filePath+name;
      //發起請求 bucketName就是oss建立的bucketName
        ossClient.putObject(bucketName, fileName, inputStream);
        //uploadUrl 就是由bucketName+region組成的路徑
        String url = uploadUrl + "/" + fileName;
        return url;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

}

返回oss的圖片路徑,再發起微信授權的時候把這個路徑儲存到資料庫
在使用者 token沒失效的時候可以使用這個路徑
如果失效了得重新上傳,這裡不知道怎麼解決好

相關文章