You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ballerina REST服务中如何对byte[]进行Base64解码?

解决方案

在Ballerina Swan Lake Update 3中,Base64编码/解码相关功能被统一放在crypto模块中,你可以按照以下步骤实现解码:

  1. 首先导入crypto模块:
import ballerina/crypto;
  1. 将获取到的二进制payload转换为字符串(因为Base64编码内容本质是字符串的字节形式),再通过crypto:base64Decode解码为原始字节数组:

完整代码示例:

import ballerina/http;
import ballerina/crypto;

resource function post-file(http:Request request) returns string|error {
    byte[]|http:ClientError binaryPayload = request.getBinaryPayload();
    if binaryPayload is http:ClientError {
        return error("Error in payload");
    }

    // 将Base64编码的字节数组转换为字符串
    string base64Str = check string:fromBytes(binaryPayload);
    // 解码得到原始文件字节数组
    byte[] decodedPayload = check crypto:base64Decode(base64Str);

    // 后续可将decodedPayload上传至文件服务器
    return "success";
}

说明

  • 你之前尝试的encoding:base64Decode和io:base64Decode在Swan Lake Update 3中已被废弃或迁移,当前版本需使用crypto模块的对应方法。
  • string:fromBytes用于将二进制字节转换为UTF-8字符串,确保Base64编码内容能被正确识别。
  • crypto:base64Decode接受Base64字符串输入,返回解码后的原始字节数组,可直接用于文件上传操作。

内容的提问来源于stack exchange,提问作者shayanmalinda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:42:47