質問

投稿者:CW1351
登録日:2024年5月14日(火)

PHPでのファイルダウンロードについてご質問

PHPを使ったファイルのダウンロードについて検討をしております。 検証をしており、DBに入っているファイルIDを使いGoogleDriveに接続しに行く作りとなっています。 手動で実行したところ、以下の結果画面が出力されました。 天気予報などの外部APIを実行し、テキストのデータは取得できたのですが、SPIRALのサイト・DBのPHPを使いAPIを使ってファイルをダウンロードできるのでしょうか? ご教授の程、よろしくお願いいたします。

googledriveへのAPI接続
<?php
//登録されたレコードの値を取得する
$record = $SPIRAL->getRecord();

//ファイルIDを取得する
$fileId = $record ["item"]["fileId"]; 

//アクセストークンを作成
$apiKey = "googledriveへのアクセスキーを記載";

//urlを作成
$url = 'https://www.googleapis.com/drive/v3/files/' . $fileId ."?alt=media&access_token=" . $apiKey;
//print_r ($url);

// curlのセッションを初期化する
$ch = curl_init();

// curlのオプションを設定する
$options = array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);

// curlを実行し、レスポンスデータを保存する
$response = curl_exec($ch);
//curl_exec($ch);
print_r ($response);
更新日:2024年5月16日(木)
いいね

コメント

  • 現在ではAPIキー(アクセストークン)をURLに指定するのではなく、 ヘッダーに指定するようです。 また、ダウンロードしたファイルをスパイラル上でどの様にしたいのでしょうか。 ダウンロードしたファイルを確認した所バイナリデータでしたので そのバイナリデータをスパイラルv2のDBへ格納するサンプルプログラムを添付いたします。

    GoogleドライブからファイルをダウンロードしてDBへ保存
    <?php
    //googleDriveからファイルダウンロード
    $access_token = "GoogleのOAuthで取得したアクセストークンを記載";
    // ダウンロードするファイルIDを指定
    $file_id = 'ファイルIDを記載。ファイルIDの取得もGoogleドライブのAPIが必要ですが、割愛。';
    $download_url = "https://www.googleapis.com/drive/v3/files/{$file_id}?alt=media";
    
    // cURLでファイルをダウンロード
    $ch = curl_init($download_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $access_token,
    ]);
    
    $response = curl_exec($ch);
    
    if ($response === false) {
        echo 'Error: ' . curl_error($ch);
        curl_close($ch);
        exit();
    }
    curl_close($ch);
    
    
    文字数の問題で分割
    //以下ダウンロードしたファイルをDBへ保存
    
    //------------------------------
    // 設定値
    //------------------------------
    define("API_URL", "https://api.spiral-platform.com/v1");
    define("API_KEY", "APIキーを記載");
    define("APP_ROLE", "");
    define("DB_ID", "XXXXX"); //ファイルを格納するDBID
    define("APP_ID", "YYYYY"); //ファイルを格納するDBが属しているアプリID
    $fileFieldId = "1"; //ファイルフィールドID
    $fileFieldName = ""; //ファイルフィールド識別名
    $fileName = "aaa.png"; //ファイル名
    $commonBase = CommonBase::getInstance();
    
        //ファイルアップロードトークン発行
        $apiUrlPass = "/apps/". APP_ID. "/dbs/". DB_ID. "/". $fileFieldId. "/files/uploadToken";
        $apiResponse = $commonBase->apiCurlAction("POST", $apiUrlPass);
        $fileUploadToken = $apiResponse["fileUploadToken"];
        //ファイルアップロード
        $apiUrlPass = "/apps/". APP_ID. "/dbs/". DB_ID. "/". $fileFieldId. "/files";
    
            // リクエストボディ(マルチパート形式)
            $requestBody = "--WebKitFormBoundary7MA4YWxkTrZu0gW\r\n";
            $requestBody .= "Content-Disposition: form-data; name=\"file\"; filename=\"". $fileName. "\"\r\n";
            $requestBody .= "Content-Type: image/png\r\n\r\n";
            $requestBody .= $response. "\r\n";
            $requestBody .= "--WebKitFormBoundary7MA4YWxkTrZu0gW\r\n";
            $requestBody .= "Content-Disposition: form-data; name=\"fileUploadToken\"\r\n\r\n";
            $requestBody .= $fileUploadToken. "\r\n";
            $requestBody .= "--WebKitFormBoundary7MA4YWxkTrZu0gW--";
    
            $contentType = "Content-Type: multipart/form-data; boundary=WebKitFormBoundary7MA4YWxkTrZu0gW";
    
        $apiResponse = $commonBase->apiCurlAction("POST", $apiUrlPass, $requestBody, $contentType);
    
    // 登録するデータを指定
    
    $insertData = array(
        $fileFieldName  => array($apiResponse["fileKey"]),
    );
    
    $resultRecordInsert = $commonBase->apiCurlAction("POST", "/apps/". APP_ID. "/dbs/". DB_ID. "/records", $insertData);
    文字数の問題で分割
    //------------------------------
    // 共通モジュール
    //------------------------------
    class CommonBase {
        /**
         * シングルトンインスタンス
         * @var UserManager
         */
        protected static $singleton;
    
        public function __construct() {
            if (self::$singleton) {
                throw new Exception('must be singleton');
            }
            self::$singleton = $this;
        }
    
    文字数の問題で分割
        /**
         * シングルトンインスタンスを返す
         * @return UserManager
         */
        public static function getInstance() {
            if (!self::$singleton) {
                return new CommonBase();
            } else {
                return self::$singleton;
            }
        }
        /**
         * V2用 API送信ロジック
         * @return Result
         */
        function apiCurlAction($method, $addUrlPass, $data = null, $multiPart = null, $jsonDecode = null) {
            $header = array(
                "Authorization:Bearer ". API_KEY,
                "X-Spiral-Api-Version: 1.1",
            );
            if($multiPart) {
                $header = array_merge($header, array($multiPart));
            } else {
                $header = array_merge($header, array("Content-Type:application/json"));
            }
            if(APP_ROLE){
    			$header = array_merge($header, array("X-Spiral-App-Role: ".APP_ROLE));
    		}
            // curl
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_URL, API_URL. $addUrlPass);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            if ($method == "POST") {
                if ($multiPart) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                } else {
                    curl_setopt($curl, CURLOPT_POSTFIELDS , json_encode($data));
                }
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            }
            if ($method == "PATCH") {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            }
    
    
    文字数の問題で分割
            if ($method == "DELETE") {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            }
            $response = curl_exec($curl);
            if (curl_errno($curl)) echo curl_error($curl);
            curl_close($curl);
            if($jsonDecode){
    			return $response;
    		}else{
                return json_decode($response, true);
    		}
        }
    }
    ?>
    • いいね
    2024年5月14日(火)
  • CW1351

    情報のご提供ありがとうございます。 アクセストークンの指定についても方法が変わっていたのですね… できるかどうかの検証段階だったのですが、 具体的なプログラムをいただきとても助かりました。 ご教授ありがとうございました。

    • いいね
    2024年5月16日(木)
あなたもログインして、
回答してみませんか?