上传Base64转Bytes对象到S3触发ValueError错误求助
解决S3上传Base64字符串时的ValueError问题
错误原因
upload_fileobj方法要求传入的fileobj必须实现read方法,你解码后得到的img_content是bytes类型,不具备这个方法,因此触发ValueError: Fileobj must implement read。
解决方案
以下两种方法都能满足你“不存储本地文件,直接处理Base64字符串”的需求:
方法1:用io.BytesIO包装bytes为类文件对象
适合大文件,支持分块上传:
import base64 import io import boto3 # 初始化S3客户端(根据你的配置调整) client = boto3.client('s3', aws_access_key_id='your_access_key', aws_secret_access_key='your_secret_key') with open(base64_txt_file, 'r') as file: base64_content = file.read() # 解码Base64字符串为bytes img_content = base64.b64decode(base64_content) # 将bytes包装成类文件对象,并重设文件指针到开头 img_fileobj = io.BytesIO(img_content) img_fileobj.seek(0) object_name = 'sample.jpeg' # 上传到S3 client.upload_fileobj(img_fileobj, bucket_name, object_name, ExtraArgs={'ACL': 'public-read'}) # 生成公共URL public_url = f"https://{bucket_name}.s3.amazonaws.com/{object_name}" print(public_url)
方法2:直接使用put_object上传bytes
更简洁,适合小文件(建议文件大小在100MB以内):
import base64 import boto3 # 初始化S3客户端(根据你的配置调整) client = boto3.client('s3', aws_access_key_id='your_access_key', aws_secret_access_key='your_secret_key') with open(base64_txt_file, 'r') as file: base64_content = file.read() # 解码Base64字符串为bytes img_content = base64.b64decode(base64_content) object_name = 'sample.jpeg' # 上传到S3,指定ContentType确保浏览器正确识别图片 client.put_object( Bucket=bucket_name, Key=object_name, Body=img_content, ACL='public-read', ContentType='image/jpeg' ) # 生成公共URL public_url = f"https://{bucket_name}.s3.amazonaws.com/{object_name}" print(public_url)
注意事项
- 如果你是直接从API接收Base64字符串,跳过
open读取文件的步骤,直接用API返回的字符串解码即可。 - 使用
put_object时建议指定ContentType,否则S3会默认将文件类型设为binary/octet-stream,可能导致浏览器无法直接预览图片。
内容的提问来源于stack exchange,提问作者Amit Pathak
相关产品推荐
相关产品推荐

