azure-blob-storagepython-3.8

quote_from_bytes() expected bytes error when data is in bytes format when uploading to blob storage in Python3


Can someone tell me what I am doing wrong with trying to upload an image to blob storage? Below is my code.

print(type(img['image'])) #Output is <class 'bytes'>

connection_string = get_blob_connection_string()
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
blob_client = blob_service_client.get_blob_client(container="images", blob=img['id'])

exists = blob_client.exists()
if (exists == False):
    result = blob_client.upload_blob(img['image'], blob_type="blockblob")
    print(result)

When inserting the blob, it throws the error

quote_from_bytes() expected bytes

This error makes no sense, I gave it bytes. What am I missing?


Solution

  • After reproducing from my end, I have received the same issue. You are receiving this error because of incompatible type of the file (i.e., file format).

    enter image description here

    After changing the below line to the correct format I could able to achieve your requirement.

    blob_client = blob_service_client.get_blob_client(container="images", blob=img['id'])
    

    Below is the correct format

    blob_client=blob_service_client.get_blob_client(container='container', blob='<LOCAL FILE PATH>');
    

    Below is the complete code that worked for me

    from  azure.storage.blob  import  BlobServiceClient
    from  PIL  import  Image
    
    connection_string = "<CONNECTION STRING>"
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    blob_client=blob_service_client.get_blob_client(container='container', blob='<LOCALPATH>');
    
    with  open(file='<PATH IN YOUR STORAGE ACCOUNT WITH FILE NAME>', mode="rb") as  data:
    
    blob_client.upload_blob(data)
    

    RESULTS:

    enter image description here