| from flask import Flask, request, render_template_string, jsonify |
| from google.cloud import storage |
| import os |
| import tempfile |
|
|
| app = Flask(__name__) |
|
|
| |
| def upload_to_gcs(bucket_name, file_path, destination_blob_name): |
| |
| storage_client = storage.Client.create_anonymous_client() |
|
|
| |
| bucket = storage_client.bucket(bucket_name) |
| blob = bucket.blob(destination_blob_name) |
|
|
| |
| blob.upload_from_filename(file_path) |
| print(f"File {file_path} uploaded to {destination_blob_name}.") |
|
|
| |
| if os.path.exists(file_path): |
| os.remove(file_path) |
|
|
| |
| @app.route('/', methods=['GET']) |
| def index(): |
| |
| upload_form_html = ''' |
| <!DOCTYPE html> |
| <html lang="ja"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>ファイルアップロード</title> |
| </head> |
| <body> |
| <h1>Google Cloud Storageへのファイルアップロード</h1> |
| <form action="/upload" method="post" enctype="multipart/form-data"> |
| <label for="file">アップロードするファイルを選択:</label> |
| <input type="file" name="file" id="file" required> |
| <button type="submit">アップロード</button> |
| </form> |
| </body> |
| </html> |
| ''' |
| return render_template_string(upload_form_html) |
|
|
| |
| @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 |
|
|
| |
| with tempfile.NamedTemporaryFile(delete=False) as temp_file: |
| temp_file.write(file.read()) |
| temp_file.close() |
| |
| |
| upload_to_gcs('s4s-api-bucket', temp_file.name, file.filename) |
|
|
| |
| return jsonify({'message': 'File successfully uploaded to GCS'}), 200 |
|
|
| if __name__ == '__main__': |
| app.run(debug=True, host="0.0.0.0", port=7860) |
|
|