0

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?

2 Answers 2

0

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

2
  • In your example, you have the file locally on disk. Is it not possible to do this with a byte array already in memory? In my situation, I am reading the image directly from an online source, so it never ends up as a file on the disk. I suppose I could write it to a temp file and delete it, but that seems like the wrong way of doing things.
    – Dave
    Commented Feb 2, 2023 at 19:07
  • It looks like things will work if it is given a path, regardless of the path actually exists on disk.
    – Dave
    Commented Feb 2, 2023 at 23:59
-1

Another cause for this error is to provide BlobServiceClient.get_blob_client with a Path object as blob name (blob parameter). In this case, you must do the cast to string yourself:

file_path = Path("my_path")
blob_client = blob_service_client.get_blob_client(container="my_container", blob=str(file_path))

The same error occurs for ContainerClient.get_blob_client, ContainerClient.upload_blob and probably other related methods.

Not the answer you're looking for? Browse other questions tagged or ask your own question.