Azure Blob Storage + Python Flask - File Upload, Download, and Delete Example


To implement file upload, download, and delete functionalities using Azure Blob Storage and Python Flask, follow these steps:

1. Install Required Packages

You will need to install flask and azure-storage-blob Python libraries.

pip install flask azure-storage-blob

2. Set Up Azure Blob Storage

Ensure you have an Azure Storage account and a Blob container. You'll need the connection string and container name for authentication.

3. Create Flask App

Here’s a simple example that demonstrates how to implement file upload, download, and delete in Flask using Azure Blob Storage:

import os
from flask import Flask, request, send_from_directory, jsonify
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

app = Flask(__name__)

# Azure Storage connection string and container name
AZURE_STORAGE_CONNECTION_STRING = 'your_connection_string_here'
CONTAINER_NAME = 'your_container_name_here'

# Initialize the BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(AZURE_STORAGE_CONNECTION_STRING)
container_client = blob_service_client.get_container_client(CONTAINER_NAME)

# File upload endpoint
@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # Upload to Azure Blob Storage
    try:
        blob_client = container_client.get_blob_client(file.filename)
        blob_client.upload_blob(file)
        return jsonify({"message": f"File '{file.filename}' uploaded successfully!"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# File download endpoint
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    try:
        blob_client = container_client.get_blob_client(filename)
        download_stream = blob_client.download_blob()
        
        # Save the blob to a local file (optional)
        download_path = os.path.join('downloads', filename)
        with open(download_path, "wb") as file:
            file.write(download_stream.readall())

        return send_from_directory('downloads', filename), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# File delete endpoint
@app.route('/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
    try:
        blob_client = container_client.get_blob_client(filename)
        blob_client.delete_blob()
        return jsonify({"message": f"File '{filename}' deleted successfully!"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    # Create download directory if it doesn't exist
    if not os.path.exists('downloads'):
        os.makedirs('downloads')

    app.run(debug=True)

4. Explanation:

  • Upload Endpoint (/upload): Accepts a file in the POST request. The file is uploaded to Azure Blob Storage using the upload_blob method.

  • Download Endpoint (/download/<filename>): Allows downloading a file from Azure Blob Storage. The file is retrieved using the download_blob method and sent to the client using Flask's send_from_directory.

  • Delete Endpoint (/delete/<filename>): Deletes a specified file from Azure Blob Storage using the delete_blob method.

5. Running the Flask App

Run the Flask app:

python app.py

You can now test the upload, download, and delete functionalities using POST, GET, and DELETE requests.

6. Testing the Endpoints

  • Upload: Use a tool like Postman to send a POST request to http://localhost:5000/upload with a file attached.

  • Download: To download a file, make a GET request to http://localhost:5000/download/<filename>.

  • Delete: To delete a file, make a DELETE request to http://localhost:5000/delete/<filename>.

Notes:

  • Replace your_connection_string_here with your actual Azure Blob Storage connection string.
  • Ensure your Azure Blob container is set up correctly and has proper permissions.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete