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

使用API Gateway和Lambda向Smartsheet附加PDF的Base64解码问题

问题描述

通过API Gateway和Lambda向Smartsheet的行附加PDF文件时,请求体包含疑似Unicode格式的字符串,执行以下代码时触发Non-base64 digit found错误:

temp = tempfile.NamedTemporaryFile()
with open(temp.name, "wb") as file:
        file_content = base64.b64decode(bytes(event['body'], 'utf-8'), validate=True)
        file.write(file_content)
        
response = smartsheet_client.Attachments.attach_file_to_row(1234, 1234, (
        'test.pdf',
        open(temp.name, "rb"),
        "application/pdf"
    ))

将validate=True改为False后错误消失,但希望找到正确的解码方式,确保PDF能正常写入并发送到Smartsheet。

解决方案

问题出在哪

请求体里的字符串不是纯Base64格式,主要两个原因:

  • API Gateway可能把原始请求体做了Unicode转义,变成带\uXXXX的字符串
  • 字符串里混了换行、空格这类非Base64允许的字符,validate=True时就会报错

正确处理步骤

  1. 转义回正常字符串:如果event['body']是带\uXXXX的格式,先把它转成真实的Base64字符串
  2. 清理无效字符:把所有Base64不允许的字符(仅保留A-Za-z0-9+/=)都删掉
  3. 安全解码写文件:用清理后的字符串解码,保留validate=True提前发现无效数据

修正后的代码

import tempfile
import base64
import re
import os

def lambda_handler(event, context):
    # 处理Unicode转义的请求体
    raw_body = event['body']
    decoded_body = raw_body.encode('utf-8').decode('unicode-escape')
    
    # 清理Base64字符串,移除非法字符
    clean_base64 = re.sub(r'[^A-Za-z0-9+/=]', '', decoded_body)
    
    # 创建临时文件(设delete=False避免自动删除)
    temp = tempfile.NamedTemporaryFile(delete=False)
    try:
        with open(temp.name, "wb") as file:
            file_content = base64.b64decode(clean_base64, validate=True)
            file.write(file_content)
        
        # 附加PDF到Smartsheet行
        response = smartsheet_client.Attachments.attach_file_to_row(
            1234, 
            1234, 
            ('test.pdf', open(temp.name, "rb"), "application/pdf")
        )
        return {'statusCode': 200, 'body': 'Attachment successful'}
    finally:
        # 清理临时文件
        os.unlink(temp.name)

额外提示

如果API Gateway用了Lambda Proxy Integration,可以先检查event['isBase64Encoded']字段:如果值为True,直接用base64.b64decode(event['body'], validate=True)即可,无需处理Unicode转义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:11:00