我想使用 python 将流(StringIO | 字节)作为 blob 添加到 Azure 容器中。当我上传它时,它似乎被编码了。所以我使用了下面的代码。
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)
有人可以帮我解决这个问题吗?
我在我的环境中尝试了以下 python 代码,将流作为 blob 添加到 Azure 容器中,并得到以下结果:
代码:
def uploadBlobStream(blobServiceClient: BlobServiceClient, containerName, stream, blobName):
blobClient = blobServiceClient.get_blob_client(container=containerName, blob=blobName)
if isinstance(stream, str):
inputStream = io.BytesIO(stream.encode())
elif isinstance(stream, bytes):
inputStream = io.BytesIO(stream)
else:
raise ValueError("Some error")
blobClient.upload_blob(inputStream.getvalue(), blob_type="BlockBlob")
connectionString = "your-connection-string"
containerName = "newcontainer"
blobName = "testblob"
string_data = "Welcome to my school"
blobServiceClient = BlobServiceClient.from_connection_string(connectionString)
uploadBlobStream(blobServiceClient, containerName, string_data.encode(), blobName)
输出:
本地:
传送门: Blob 已成功上传到 Azure 门户中的容器。
当我下载 blob 时,它看起来像下面这样,