How to download the image file from azure shared file storage and save it to specific…
- User
How to download the image file from azure shared file storage and save it to specific local directory in python
Assistant
Downloading an image file from Azure File Storage and saving it to a specific local directory involves using the Azure Files SDK. Here's a comprehensive guide with different authentication methods.
Prerequisites
Before you start, make sure you have:
- Azure Storage Account: An active Azure subscription and a storage account created.
- File Share: A file share within your storage account where your image files are stored.
- Image File: At least one image file (e.g.,
my_image.jpg) uploaded to that file share. - Python Installed: Python 3.7+ is recommended.
- Azure Storage File Share SDK: Install the necessary Python package:
bash
pip install azure-storage-file-share azure-identity
Method 1: Using Connection String (Recommended for Quick Start/Development)
1. Get your Storage Account Connection String:
- Go to your Azure Storage Account in the Azure Portal.
- Navigate to Access keys under Security + networking.
- Copy one of the
Connection stringvalues.
2. Python Code:
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.core.exceptions import ResourceNotFoundError # --- Configuration --- # 1. Replace with your actual connection string CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=yourstorageaccountname;AccountKey=YOUR_ACCOUNT_KEY_HERE;EndpointSuffix=core.windows.net" # 2. Replace with the name of your file share SHARE_NAME = "your-file-share" # 3. Replace with the path to your image file in the file share # Examples: # - "my_image.jpg" (file in root directory) # - "images/my_image.jpg" (file in 'images' subdirectory) # - "folder1/subfolder/my_image.jpg" (nested directories) FILE_PATH = "my_image.jpg" # 4. The local directory where you want to save the image LOCAL_DOWNLOAD_DIRECTORY = "downloaded_images" # 5. The desired filename for the downloaded image LOCAL_FILENAME = "downloaded_my_image.jpg" # Or, to keep the original name: LOCAL_FILENAME = os.path.basename(FILE_PATH) # --- End Configuration --- def download_file_from_share(connection_string, share_name, file_path, local_directory, local_filename): """ Downloads a file from Azure File Storage to a local file. """ local_file_path = os.path.join(local_directory, local_filename) try: # Create the ShareServiceClient object share_service_client = ShareServiceClient.from_connection_string(connection_string) # Get a client for the specific share share_client = share_service_client.get_share_client(share_name) # Get a client for the specific file file_client = share_client.get_file_client(file_path) print(f"Attempting to download '{file_path}' from share '{share_name}'...") # Ensure the local directory exists os.makedirs(local_directory, exist_ok=True) # Download the file data with open(local_file_path, "wb") as download_file: data = file_client.download_file() download_file.write(data.readall()) print(f"Successfully downloaded '{file_path}' to '{local_file_path}'") except ResourceNotFoundError: print(f"Error: File '{file_path}' not found in share '{share_name}'.") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == "__main__": download_file_from_share( CONNECTION_STRING, SHARE_NAME, FILE_PATH, LOCAL_DOWNLOAD_DIRECTORY, LOCAL_FILENAME )
Method 2: Using Azure AD / DefaultAzureCredential (Recommended for Production)
1. Setup Azure AD Authentication and Permissions:
- Go to your Azure Storage Account in the Azure Portal.
- Navigate to Access control (IAM).
- Click + Add -> Add role assignment.
- Search for and select the role "Storage File Data SMB Share Reader" or "Storage File Data SMB Share Contributor".
- Assign it to your Managed Identity, Service Principal, or User account.
2. Python Code:
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.identity import DefaultAzureCredential from azure.core.exceptions import ResourceNotFoundError # --- Configuration --- # 1. Your Storage Account Name (not the full URL) ACCOUNT_NAME = "yourstorageaccountname" # 2. Replace with the name of your file share SHARE_NAME = "your-file-share" # 3. Replace with the path to your image file in the file share FILE_PATH = "my_image.jpg" # 4. The local directory where you want to save the image LOCAL_DOWNLOAD_DIRECTORY = "downloaded_images" # 5. The desired filename for the downloaded image LOCAL_FILENAME = "downloaded_my_image.jpg" # --- End Configuration --- def download_file_with_aad(account_name, share_name, file_path, local_directory, local_filename): """ Downloads a file from Azure File Storage using Azure AD authentication. """ local_file_path = os.path.join(local_directory, local_filename) share_service_url = f"https://{account_name}.file.core.windows.net" try: # Create DefaultAzureCredential credential = DefaultAzureCredential() # Create the ShareServiceClient object with the credential share_service_client = ShareServiceClient(account_url=share_service_url, credential=credential) # Get a client for the specific share share_client = share_service_client.get_share_client(share_name) # Get a client for the specific file file_client = share_client.get_file_client(file_path) print(f"Attempting to download '{file_path}' from share '{share_name}' using AAD...") # Ensure the local directory exists os.makedirs(local_directory, exist_ok=True) # Download the file data with open(local_file_path, "wb") as download_file: data = file_client.download_file() download_file.write(data.readall()) print(f"Successfully downloaded '{file_path}' to '{local_file_path}'") except ResourceNotFoundError: print(f"Error: File '{file_path}' not found in share '{share_name}'.") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == "__main__": download_file_with_aad( ACCOUNT_NAME, SHARE_NAME, FILE_PATH, LOCAL_DOWNLOAD_DIRECTORY, LOCAL_FILENAME )
Method 3: Using Account Key
1. Get your Storage Account Key:
- Go to your Azure Storage Account in the Azure Portal.
- Navigate to Access keys under Security + networking.
- Copy one of the
Keyvalues (not the connection string).
2. Python Code:
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.core.exceptions import ResourceNotFoundError # --- Configuration --- # 1. Your Storage Account Name ACCOUNT_NAME = "yourstorageaccountname" # 2. Your Storage Account Key ACCOUNT_KEY = "YOUR_ACCOUNT_KEY_HERE" # 3. Replace with the name of your file share SHARE_NAME = "your-file-share" # 4. Replace with the path to your image file in the file share FILE_PATH = "my_image.jpg" # 5. The local directory where you want to save the image LOCAL_DOWNLOAD_DIRECTORY = "downloaded_images" # 6. The desired filename for the downloaded image LOCAL_FILENAME = "downloaded_my_image.jpg" # --- End Configuration --- def download_file_with_key(account_name, account_key, share_name, file_path, local_directory, local_filename): """ Downloads a file from Azure File Storage using account key authentication. """ local_file_path = os.path.join(local_directory, local_filename) share_service_url = f"https://{account_name}.file.core.windows.net" try: # Create the ShareServiceClient object with account key share_service_client = ShareServiceClient(account_url=share_service_url, credential=account_key) # Get a client for the specific share share_client = share_service_client.get_share_client(share_name) # Get a client for the specific file file_client = share_client.get_file_client(file_path) print(f"Attempting to download '{file_path}' from share '{share_name}' using account key...") # Ensure the local directory exists os.makedirs(local_directory, exist_ok=True) # Download the file data with open(local_file_path, "wb") as download_file: data = file_client.download_file() download_file.write(data.readall()) print(f"Successfully downloaded '{file_path}' to '{local_file_path}'") except ResourceNotFoundError: print(f"Error: File '{file_path}' not found in share '{share_name}'.") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == "__main__": download_file_with_key( ACCOUNT_NAME, ACCOUNT_KEY, SHARE_NAME, FILE_PATH, LOCAL_DOWNLOAD_DIRECTORY, LOCAL_FILENAME )
Advanced Example: Download Multiple Files or Browse Directories
Here's an example that shows how to list files in a directory and download multiple files:
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.core.exceptions import ResourceNotFoundError # Configuration CONNECTION_STRING = "your_connection_string_here" SHARE_NAME = "your-file-share" REMOTE_DIRECTORY = "images" # Directory in the file share, or "" for root LOCAL_DOWNLOAD_DIRECTORY = "downloaded_images" def list_and_download_files(connection_string, share_name, remote_directory, local_directory): """ Lists files in a directory and downloads them all. """ try: # Create the ShareServiceClient object share_service_client = ShareServiceClient.from_connection_string(connection_string) share_client = share_service_client.get_share_client(share_name) # Get directory client if remote_directory: directory_client = share_client.get_directory_client(remote_directory) else: directory_client = share_client.get_directory_client("") print(f"Listing files in directory '{remote_directory or 'root'}'...") # List all files and directories files_and_dirs = list(directory_client.list_directories_and_files()) # Filter only files (not directories) files = [item for item in files_and_dirs if not item.get('is_directory', False)] print(f"Found {len(files)} files to download") # Ensure local directory exists os.makedirs(local_directory, exist_ok=True) # Download each file for file_item in files: file_name = file_item['name'] # Construct the full file path in the share if remote_directory: file_path = f"{remote_directory}/{file_name}" else: file_path = file_name # Local file path local_file_path = os.path.join(local_directory, file_name) try: # Get file client and download file_client = share_client.get_file_client(file_path) print(f"Downloading '{file_path}'...") with open(local_file_path, "wb") as download_file: data = file_client.download_file() download_file.write(data.readall()) print(f"Successfully downloaded '{file_path}' to '{local_file_path}'") except Exception as e: print(f"Error downloading '{file_path}': {e}") except ResourceNotFoundError: print(f"Error: Directory '{remote_directory}' not found in share '{share_name}'.") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == "__main__": list_and_download_files( CONNECTION_STRING, SHARE_NAME, REMOTE_DIRECTORY, LOCAL_DOWNLOAD_DIRECTORY )
Key Differences from Blob Storage:
- URL Structure: File storage uses
.file.core.windows.netinstead of.blob.core.windows.net - Hierarchical Structure: Azure Files supports true directory structures, unlike blob storage's flat namespace with virtual folders
- File Paths: Use forward slashes (
/) to separate directories in file paths - Permissions: Different RBAC roles are needed (Storage File Data SMB Share roles instead of Storage Blob Data roles)
Best Practices:
- Security: Use Azure AD authentication (Method 2) for production environments
- Error Handling: Implement robust error handling for network issues and missing files
- Large Files: For very large files, consider downloading in chunks to manage memory usage
- Path Handling: Use
os.path.join()for local paths and forward slashes for Azure file paths - Directory Creation: Always ensure local directories exist before downloading files
This approach works for any file type stored in Azure File Storage, not just images. Simply adjust the file paths and names according to your specific use case.
- User
Besides the downloading function, I want to know how to list files in a directory and upload local file to Azure share file storage
Assistant
Here's a comprehensive guide covering listing files in directories and uploading local files to Azure File Storage, along with the downloading functionality.
Complete Azure File Storage Operations
Prerequisites
bashpip install azure-storage-file-share azure-identity
1. Listing Files and Directories
Basic Directory Listing
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.core.exceptions import ResourceNotFoundError # Configuration CONNECTION_STRING = "your_connection_string_here" SHARE_NAME = "your-file-share" def list_files_and_directories(connection_string, share_name, directory_path=""): """ Lists all files and directories in a specified directory. Args: directory_path: Path to directory in share (empty string for root) """ try: # Create the ShareServiceClient object share_service_client = ShareServiceClient.from_connection_string(connection_string) share_client = share_service_client.get_share_client(share_name) # Get directory client if directory_path: directory_client = share_client.get_directory_client(directory_path) print(f"Listing contents of directory: '{directory_path}'") else: directory_client = share_client.get_directory_client("") print("Listing contents of root directory") # List all items items = list(directory_client.list_directories_and_files()) if not items: print("Directory is empty") return print(f"\nFound {len(items)} items:") print("-" * 50) directories = [] files = [] for item in items: if item.get('is_directory', False): directories.append(item) print(f"📁 [DIR] {item['name']}") else: files.append(item) size_mb = item.get('size', 0) / (1024 * 1024) print(f"📄 [FILE] {item['name']} ({size_mb:.2f} MB)") print(f"\nSummary: {len(directories)} directories, {len(files)} files") return {'directories': directories, 'files': files} except ResourceNotFoundError: print(f"Error: Directory '{directory_path}' not found in share '{share_name}'.") except Exception as e: print(f"An unexpected error occurred: {e}") # Example usage if __name__ == "__main__": # List root directory list_files_and_directories(CONNECTION_STRING, SHARE_NAME) # List specific directory list_files_and_directories(CONNECTION_STRING, SHARE_NAME, "images")Recursive Directory Listing
pythondef list_files_recursively(connection_string, share_name, directory_path="", level=0): """ Recursively lists all files and directories in a share. """ try: share_service_client = ShareServiceClient.from_connection_string(connection_string) share_client = share_service_client.get_share_client(share_name) # Get directory client directory_client = share_client.get_directory_client(directory_path) # Indentation for nested display indent = " " * level if level == 0: print(f"📁 {share_name}/ (root)") # List all items items = list(directory_client.list_directories_and_files()) for item in items: if item.get('is_directory', False): # It's a directory dir_name = item['name'] print(f"{indent}📁 {dir_name}/") # Recursively list subdirectory subdirectory_path = f"{directory_path}/{dir_name}" if directory_path else dir_name list_files_recursively(connection_string, share_name, subdirectory_path, level + 1) else: # It's a file file_name = item['name'] size_mb = item.get('size', 0) / (1024 * 1024) print(f"{indent}📄 {file_name} ({size_mb:.2f} MB)") except ResourceNotFoundError: print(f"{indent}❌ Directory not found: '{directory_path}'") except Exception as e: print(f"{indent}❌ Error: {e}") # Example usage if __name__ == "__main__": list_files_recursively(CONNECTION_STRING, SHARE_NAME)
2. Uploading Files to Azure File Storage
Basic File Upload
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError # Configuration CONNECTION_STRING = "your_connection_string_here" SHARE_NAME = "your-file-share" def upload_file_to_share(connection_string, share_name, local_file_path, remote_file_path, overwrite=False): """ Uploads a local file to Azure File Storage. Args: local_file_path: Path to the local file to upload remote_file_path: Path where the file should be stored in the share overwrite: Whether to overwrite if file already exists """ try: # Check if local file exists if not os.path.exists(local_file_path): print(f"Error: Local file '{local_file_path}' not found.") return False # Create the ShareServiceClient object share_service_client = ShareServiceClient.from_connection_string(connection_string) share_client = share_service_client.get_share_client(share_name) # Create directories if they don't exist remote_dir = os.path.dirname(remote_file_path) if remote_dir: create_directories(share_client, remote_dir) # Get file client file_client = share_client.get_file_client(remote_file_path) print(f"Uploading '{local_file_path}' to '{remote_file_path}'...") # Get file size file_size = os.path.getsize(local_file_path) print(f"File size: {file_size / (1024 * 1024):.2f} MB") # Upload the file with open(local_file_path, "rb") as source_file: file_client.upload_file(source_file, overwrite=overwrite) print(f"Successfully uploaded '{local_file_path}' to '{remote_file_path}'") return True except ResourceExistsError: print(f"Error: File '{remote_file_path}' already exists. Use overwrite=True to replace it.") return False except Exception as e: print(f"An unexpected error occurred: {e}") return False def create_directories(share_client, directory_path): """ Creates directories recursively if they don't exist. """ if not directory_path: return # Split path into components path_parts = directory_path.split('/') current_path = "" for part in path_parts: if current_path: current_path += f"/{part}" else: current_path = part try: directory_client = share_client.get_directory_client(current_path) directory_client.create_directory() print(f"Created directory: '{current_path}'") except ResourceExistsError: # Directory already exists, which is fine pass except Exception as e: print(f"Error creating directory '{current_path}': {e}") # Example usage if __name__ == "__main__": # Upload a single file upload_file_to_share( CONNECTION_STRING, SHARE_NAME, "local_images/my_photo.jpg", # Local file path "images/uploaded_photo.jpg", # Remote file path overwrite=True )Upload Multiple Files
pythondef upload_directory(connection_string, share_name, local_directory, remote_directory="", file_extensions=None): """ Uploads all files from a local directory to Azure File Storage. Args: local_directory: Local directory containing files to upload remote_directory: Remote directory in the share (empty for root) file_extensions: List of file extensions to filter (e.g., ['.jpg', '.png']) """ try: if not os.path.exists(local_directory): print(f"Error: Local directory '{local_directory}' not found.") return share_service_client = ShareServiceClient.from_connection_string(connection_string) share_client = share_service_client.get_share_client(share_name) # Create remote directory if specified if remote_directory: create_directories(share_client, remote_directory) uploaded_count = 0 failed_count = 0 # Walk through local directory for root, dirs, files in os.walk(local_directory): for file_name in files: # Filter by file extensions if specified if file_extensions: file_ext = os.path.splitext(file_name)[1].lower() if file_ext not in file_extensions: continue # Construct paths local_file_path = os.path.join(root, file_name) # Calculate relative path from local_directory relative_path = os.path.relpath(local_file_path, local_directory) # Construct remote path if remote_directory: remote_file_path = f"{remote_directory}/{relative_path}".replace("\\", "/") else: remote_file_path = relative_path.replace("\\", "/") # Upload file success = upload_file_to_share( connection_string, share_name, local_file_path, remote_file_path, overwrite=True ) if success: uploaded_count += 1 else: failed_count += 1 print(f"\nUpload completed: {uploaded_count} files uploaded, {failed_count} failed") except Exception as e: print(f"An unexpected error occurred: {e}") # Example usage if __name__ == "__main__": # Upload all images from local directory upload_directory( CONNECTION_STRING, SHARE_NAME, "local_images", # Local directory "uploaded_images", # Remote directory ['.jpg', '.jpeg', '.png', '.gif'] # Only image files )
3. Complete Example with All Operations
pythonimport os from azure.storage.fileshare import ShareServiceClient from azure.identity import DefaultAzureCredential from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError class AzureFileStorageManager: """ A comprehensive class for managing Azure File Storage operations. """ def __init__(self, account_name=None, connection_string=None, credential=None): """ Initialize with either connection string or Azure AD credentials. """ if connection_string: self.share_service_client = ShareServiceClient.from_connection_string(connection_string) elif account_name and credential: account_url = f"https://{account_name}.file.core.windows.net" self.share_service_client = ShareServiceClient(account_url=account_url, credential=credential) else: raise ValueError("Provide either connection_string or (account_name + credential)") def list_shares(self): """List all file shares in the storage account.""" try: shares = list(self.share_service_client.list_shares()) print(f"Found {len(shares)} shares:") for share in shares: print(f" 📁 {share.name}") return shares except Exception as e: print(f"Error listing shares: {e}") return [] def list_directory_contents(self, share_name, directory_path=""): """List contents of a directory.""" try: share_client = self.share_service_client.get_share_client(share_name) directory_client = share_client.get_directory_client(directory_path) items = list(directory_client.list_directories_and_files()) print(f"Contents of '{directory_path or 'root'}' in share '{share_name}':") for item in items: if item.get('is_directory', False): print(f" 📁 {item['name']}/") else: size_mb = item.get('size', 0) / (1024 * 1024) print(f" 📄 {item['name']} ({size_mb:.2f} MB)") return items except Exception as e: print(f"Error listing directory: {e}") return [] def upload_file(self, share_name, local_file_path, remote_file_path, overwrite=False): """Upload a single file.""" try: if not os.path.exists(local_file_path): print(f"Local file not found: {local_file_path}") return False share_client = self.share_service_client.get_share_client(share_name) # Create directories if needed remote_dir = os.path.dirname(remote_file_path) if remote_dir: self._create_directories(share_client, remote_dir) file_client = share_client.get_file_client(remote_file_path) with open(local_file_path, "rb") as source_file: file_client.upload_file(source_file, overwrite=overwrite) print(f"✅ Uploaded: {local_file_path} → {remote_file_path}") return True except ResourceExistsError: print(f"❌ File exists: {remote_file_path} (use overwrite=True)") return False except Exception as e: print(f"❌ Upload failed: {e}") return False def download_file(self, share_name, remote_file_path, local_file_path): """Download a single file.""" try: share_client = self.share_service_client.get_share_client(share_name) file_client = share_client.get_file_client(remote_file_path) # Ensure local directory exists local_dir = os.path.dirname(local_file_path) if local_dir: os.makedirs(local_dir, exist_ok=True) with open(local_file_path, "wb") as download_file: data = file_client.download_file() download_file.write(data.readall()) print(f"✅ Downloaded: {remote_file_path} → {local_file_path}") return True except ResourceNotFoundError: print(f"❌ File not found: {remote_file_path}") return False except Exception as e: print(f"❌ Download failed: {e}") return False def _create_directories(self, share_client, directory_path): """Create directories recursively.""" path_parts = directory_path.split('/') current_path = "" for part in path_parts: current_path = f"{current_path}/{part}" if current_path else part try: directory_client = share_client.get_directory_client(current_path) directory_client.create_directory() except ResourceExistsError: pass # Directory
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.