我在尝试将s3响应转换为b64data时遇到ValueError: embedded null byte
我尝试过使用urllib.request
程序包,同时抛出了ValueError: embedded null byte
s3_response_object = settings.S3_CLIENT.get_object(Bucket=settings.BUCKET_NAME, Key='image_name.png')
object_content = s3_response_object['Body'].read()
with open(object_content, 'rb') as img:
b64_image = base64.b64encode(img.read())
以下是使用预签名URL尝试的其他代码
signed_uri = settings.S3_CLIENT. \
generate_presigned_url(ClientMethod='get_object',
Params={'Bucket':settings.BUCKET_NAME,
'Key': 'image_name.png'})
contents = urllib.request.urlopen(signed_uri).read()
with open(contents, "rb") as image_file:
b64_image = base64.b64encode(image_file.read())
两种方法均会引发此错误
with open(object_content, 'rb') as img:
ValueError: embedded null byte
但是使用预签名的URI,我可以打开图像,但是该图像需要作为b64data。
答案 0 :(得分:1)
您不必两次调用.read()。 object_content的类型是字节
执行以下操作:
signed_uri = settings.S3_CLIENT. \
generate_presigned_url(ClientMethod='get_object',
Params={'Bucket':settings.BUCKET_NAME,
'Key': 'image_name.png'})
contents = urllib.request.urlopen(signed_uri).read()
b64_img = base64.b64encode(contents)