Python:解决将编码流作为Blob上传至Azure容器后仍编码的问题
问题描述
我想用Python把StringIO或bytes类型的流上传到Azure容器作为Blob,但上传后内容似乎处于编码状态,尝试了以下代码仍未解决:
def upload_blob_stream(blob_service_client: BlobServiceClient, container_name,stream,encoding=None): blob_client = blob_service_client.get_blob_client(container=container_name, blob=log_blob_name) if encoding: data = stream.decode(encoding) else: data = stream input_stream = io.BytesIO(data) blob_client.upload_blob(input_stream, blob_type="BlockBlob") upload_blob_stream(blob_service_client,container_name,stream)
解决方案
问题核心是对StringIO和bytes两种流类型的处理逻辑错误,调整后即可解决:
关键修正逻辑
- bytes类型流:直接用
io.BytesIO包装后上传,无需解码操作 - StringIO类型流:先将内部字符串编码为bytes,再用
io.BytesIO包装
修改后的代码
import io from azure.storage.blob import BlobServiceClient def upload_blob_stream(blob_service_client: BlobServiceClient, container_name, blob_name, stream, encoding='utf-8'): blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name) # 根据流类型做针对性处理 if isinstance(stream, io.StringIO): # StringIO内容转bytes后包装为BytesIO content_bytes = stream.getvalue().encode(encoding) input_stream = io.BytesIO(content_bytes) elif isinstance(stream, bytes): # bytes直接包装为BytesIO input_stream = io.BytesIO(stream) else: # 兼容已有的BytesIO或其他可读取流 input_stream = stream # 可选添加overwrite=True覆盖已有Blob blob_client.upload_blob(input_stream, blob_type="BlockBlob", overwrite=True) # 调用示例 # 1. 上传bytes流 # upload_blob_stream(blob_service_client, "my-container", "test-bin.blob", b"raw byte content") # 2. 上传StringIO流 # s_stream = io.StringIO("中文测试内容") # upload_blob_stream(blob_service_client, "my-container", "test-txt.blob", s_stream)
额外说明
- 原代码中
log_blob_name未定义,需改为传入的blob_name参数 - 若需要覆盖容器中已存在的同名Blob,添加
overwrite=True参数即可
内容的提问来源于stack exchange,提问作者Asu
相关产品推荐
相关产品推荐

