File size: 2,457 Bytes
8ab1d78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c37e21
8ab1d78
 
 
 
 
2532a8e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from flask import Flask, request, render_template_string, jsonify
from google.cloud import storage
import os
import tempfile

app = Flask(__name__)

# Google Cloud Storageにアップロードする関数
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():
    # HTMLフォームを直接Pythonの文字列として定義
    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()
        
        # GCSにアップロード
        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)