Google Cloud Storage + Python Flask - File Upload, Download, List, and Delete Example


Here’s an example of how to use Google Cloud Storage with Python Flask for file upload, download, list, and delete operations. You’ll need to install the google-cloud-storage library and set up your Google Cloud project with the necessary credentials.

Prerequisites:

  1. Install the required packages:

    pip install Flask google-cloud-storage
  2. Set up your Google Cloud project and service account credentials. Download the JSON credentials file and set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of the file:

    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-service-account-file.json"

Flask Application with Google Cloud Storage Integration

from flask import Flask, request, jsonify, send_file
from google.cloud import storage
import os

app = Flask(__name__)

# Initialize Google Cloud Storage client
storage_client = storage.Client()

# Your Google Cloud bucket name
BUCKET_NAME = 'your-bucket-name'

# Upload a file to Google Cloud Storage
@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

    # Get the bucket
    bucket = storage_client.bucket(BUCKET_NAME)
    
    # Upload the file to the bucket
    blob = bucket.blob(file.filename)
    blob.upload_from_file(file)

    return jsonify({"message": "File uploaded successfully", "filename": file.filename}), 200

# Download a file from Google Cloud Storage
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    bucket = storage_client.bucket(BUCKET_NAME)
    blob = bucket.blob(filename)
    
    if not blob.exists():
        return jsonify({"error": "File not found"}), 404
    
    # Temporary download path
    temp_file = f"/tmp/{filename}"
    blob.download_to_filename(temp_file)
    
    return send_file(temp_file, as_attachment=True, attachment_filename=filename)

# List files in the Google Cloud Storage bucket
@app.route('/list', methods=['GET'])
def list_files():
    bucket = storage_client.bucket(BUCKET_NAME)
    blobs = bucket.list_blobs()
    file_list = [blob.name for blob in blobs]
    return jsonify({"files": file_list}), 200

# Delete a file from Google Cloud Storage
@app.route('/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
    bucket = storage_client.bucket(BUCKET_NAME)
    blob = bucket.blob(filename)

    if not blob.exists():
        return jsonify({"error": "File not found"}), 404

    blob.delete()
    return jsonify({"message": f"File {filename} deleted successfully"}), 200

if __name__ == '__main__':
    app.run(debug=True)

Explanation:

  1. Upload File (/upload):

    • Accepts a file via a POST request. It checks if the file is present and then uploads it to the specified Google Cloud Storage bucket.
  2. Download File (/download/<filename>):

    • Accepts a GET request to download a file from Google Cloud Storage. The file is temporarily downloaded to the server and sent back as an attachment.
  3. List Files (/list):

    • Accepts a GET request to list all the files in the Google Cloud Storage bucket.
  4. Delete File (/delete/<filename>):

    • Accepts a DELETE request to delete a specific file from Google Cloud Storage.

Testing:

You can test the application using tools like Postman or cURL.

  • Upload File:

    curl -X POST -F "file=@yourfile.txt" http://127.0.0.1:5000/upload
  • Download File:

    curl -O http://127.0.0.1:5000/download/yourfile.txt
  • List Files:

    curl http://127.0.0.1:5000/list
  • Delete File:

    curl -X DELETE http://127.0.0.1:5000/delete/yourfile.txt

Make sure to replace 'your-bucket-name' with your actual Google Cloud Storage bucket name.

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