Search code examples
pythonazureazure-storageazure-blob-storage

Upload image to azure blob storage using python


I have an image directory named images which contains image files as:

images
    --0001.png
    --0002.jpg
    --0003.png

Now I want to upload this directory to my azure blob storage with the same file structure. I looked at the sample code given here and here but:

  1. Even after installing azure-blob-storage, there is no such thing as BlobService in that package.
  2. Is there any place where it is clearly documented how to do this?

Solution

  • Here is my sample code works fine for me.

    import os
    from azure.storage.blob import BlockBlobService
    
    root_path = '<your root path>'
    dir_name = 'images'
    path = f"{root_path}/{dir_name}"
    file_names = os.listdir(path)
    
    account_name = '<your account name>'
    account_key = '<your account key>'
    container_name = '<your container name, such as `test` for me>'
    
    block_blob_service = BlockBlobService(
        account_name=account_name,
        account_key=account_key
    )
    
    for file_name in file_names:
        blob_name = f"{dir_name}/{file_name}"
        file_path = f"{path}/{file_name}"
        block_blob_service.create_blob_from_path(container_name, blob_name, file_path)
    

    The result as the figure below be screenshot from Azure Storage Explorer.

    enter image description here

    For more details about API references of Azure Storage SDK for Python, please refer to https://azure-storage.readthedocs.io/index.html.


    Update: My used Python version is Python 3.7.4 on Windows, and the required package is azure-storage==0.36.0, you can find it from https://pypi.org/project/azure-storage/.

    1. $ virtualenv test
    2. $ cd test
    3. $ Scripts\active
    4. $ pip install azure-storage

    Then, you can run my sample code via python upload_images.py in the current Python virtual environment.