簡體   English   中英

如何從 PHP 表單將圖像上傳到 Google Cloud Storage?

[英]How do I upload images to the Google Cloud Storage from PHP form?

我目前正在使用一個 php 應用程序將圖像上傳到 Google 雲存儲平台,但是,與我的本地服務器不同,我在弄清楚如何進行這項工作時遇到了巨大的麻煩。

這正是我想要做的:

  1. 將圖片的路徑寫入我的谷歌雲SQL
  2. 實際上傳圖片到谷歌雲存儲平台
  3. 從保存的 SQL 路徑編寫一個調用圖像的腳本,然后發布到我的網站

任何人都可以指出正確的方向嗎?

謝謝!

像這樣的東西對我有用 GAE 上的表單 - 將照片從表單通過 php 上傳到谷歌雲存儲,前提是您的文件夾權限已設置...

// get image from Form
$gs_name = $_FILES["uploaded_files"]["tmp_name"]; 
$fileType = $_FILES["uploaded_files"]["type"]; 
$fileSize = $_FILES["uploaded_files"]["size"]; 
$fileErrorMsg = $_FILES["uploaded_files"]["error"]; 
$fileExt = pathinfo($_FILES['uploaded_files']['name'], PATHINFO_EXTENSION);

// change name if you want
$fileName = 'foo.jpg';

// put to cloud storage
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
file_put_contents("gs://<bucketname>/".$fileName, $gs_name, 0, $ctx);

// or move 
$moveResult = move_uploaded_file($gs_name, 'gs://<bucketname>/'.$fileName); 

調用圖像以在您的站點上顯示的腳本是典型的 mysqli 或 pdo 方法來獲取文件名,您可以使用...

<img src="https://storage.googleapis.com/<bucketname>/<filename>"/>  

如果有人可能感興趣,我做了這個,只上傳一個文件,又快又臟:

(我不希望 php sdk 中的 500 多個文件只是為了上傳文件)

<?php
/**
 * Simple Google Cloud Storage class
 * by SAK
 */

namespace SAK;

use \Firebase\JWT\JWT;

class GCStorage {
    const 
        GCS_OAUTH2_BASE_URL = 'https://oauth2.googleapis.com/token',
        GCS_STORAGE_BASE_URL = "https://storage.googleapis.com/storage/v1/b",
        GCS_STORAGE_BASE_URL_UPLOAD = "https://storage.googleapis.com/upload/storage/v1/b";
    protected $access_token = null;
    protected $bucket = null;
    protected $scope = 'https://www.googleapis.com/auth/devstorage.read_write';
    


    function __construct($gservice_account, $private_key, $bucket) 
    {
        $this->bucket = $bucket;
        // make the JWT
        $iat = time();
        $payload = array(
            "iss" => $gservice_account,
            "scope" => $this->scope,
            "aud" => self::GCS_OAUTH2_BASE_URL,
            "iat" => $iat,
            "exp" => $iat + 3600
        );
        $jwt = JWT::encode($payload, $private_key, 'RS256');
        // echo "Encode:\n" . print_r($jwt, true) . "\n"; exit;

        $headers = array(
            "Content-Type: application/x-www-form-urlencoded"
        );

        $post_fields = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt";
        // $post_fields = array(
        //     'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        //     'assertion' => $jwt
        // );

        $curl_opts = array(
            CURLOPT_URL => self::GCS_OAUTH2_BASE_URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $post_fields,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        // var_dump($curl); exit;
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            die('Error:' . curl_error($curl));
        }
        curl_close($curl);
        $response = json_decode($response, true);
        $this->access_token = $response['access_token'];
        // echo "Resp:\n" . print_r($response, true) . "\n"; exit;
    }

    public function uploadObject($file_local_full, $file_remote_full, $content_type = 'application/octet-stream')
    {
        $url = self::GCS_STORAGE_BASE_URL_UPLOAD."/$this->bucket/o?uploadType=media&name=$file_remote_full";
    
        if(!file_exists($file_local_full)) {
            throw new \Exception("$file_local_full not found.");
        }
    
        // $filesize = filesize($file_local_full);

        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Content-Type: $content_type",
            // "Content-Length: $filesize"
        );

        // if the file is too big, it should be streamed
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => file_get_contents($file_local_full),
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

    public function uploadData(string $data, string $file_remote_full, string $content_type = 'application/octet-stream')
    {
        $url = self::GCS_STORAGE_BASE_URL_UPLOAD."/$this->bucket/o?uploadType=media&name=$file_remote_full";
    
        // $filesize = strlen($data);

        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Content-Type: $content_type",
            // "Content-Length: $filesize"
        );

        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

    public function copyObject($from, $to)
    {
        // 'https://storage.googleapis.com/storage/v1/b/[SOURCEBUCKET]/o/[SOURCEOBJECT]/copyTo/b/[DESTINATIONBUCKET]/o/[DESTINATIONOBJECT]?key=[YOUR_API_KEY]'
        $from = rawurlencode($from);
        $to = rawurlencode($to);
        $url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o/$from/copyTo/b/$this->bucket/o/$to";
        // $url = rawurlencode($url);
        
        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Accept: application/json",
            "Content-Type: application/json"
        );
    
        $payload = '{}';
    
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);
        // echo '<pre>'; var_dump($response); exit;
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

    public function deleteObject($name)
    {
        // curl -X DELETE -H "Authorization: Bearer OAUTH2_TOKEN" "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"
        //
        $name = rawurlencode($name);
        $url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o/$name";
        
        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Accept: application/json",
            "Content-Type: application/json"
        );
    
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "DELETE",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);
        // echo '<pre>'; var_dump($response); exit;
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }


    public function listObjects($folder)
    {
        // curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
        //
        $folder = rawurlencode($folder);
        $url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o?prefix=$folder";
        
        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Accept: application/json",
            "Content-Type: application/json"
        );
    
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);
        // echo '<pre>'; var_dump($response); exit;
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM