2017-07-18 107 views
0

我正嘗試使用Google Cloud Storage JSON API將圖片上傳到Google雲端存儲分區。該文件正在上傳,但沒有顯示任何內容。谷歌雲平臺 - 如何將圖像文件上傳到谷歌雲存儲桶?

<?php 

    if(isset($_POST["submit"])) 
    { 
     // Move uploaded file to a temp location 
     $uploadDir = 'temp/'; 
     $filename=$_FILES["fileToUpload"]["name"]; 
     $filesize=$_FILES["fileToUpload"]["size"]; 
     $uploadFile = $uploadDir . basename($_FILES['fileToUpload']['name']); 

     $authheaders = array(
      "Authorization: Bearer xxxxxx(my access token)", 
      "Content-Type: image/jpeg", 
      "Content-Length:".$filesize 

     ); //The access-token has to be generate everytime after one-hour. 

     if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadFile)) 
     { 
      // Prepare remote upload data 
      $uploadRequest = array(
       'fileName' => basename($uploadFile), 
       'fileData' => file_get_contents($uploadFile) 
      ); 

      // Execute remote upload 
      $curl = curl_init(); 
      $url="https://www.googleapis.com/upload/storage/v1/b/[bucket_name]/o?uploadType=media&name=".$filename; 
      curl_setopt($curl, CURLOPT_URL,$url); 
      curl_setopt($curl, CURLOPT_HTTPHEADER, $authheaders); 
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
      curl_setopt($curl, CURLOPT_TIMEOUT, 30); 
      curl_setopt($curl, CURLOPT_POST, 1);  
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($curl, CURLOPT_POSTFIELDS, $uploadRequest); 
      $response = curl_exec($curl); 
      curl_close($curl); 
      echo $response; 

     } 
    } 
?> 

我通過這個上傳圖像: -

<!DOCTYPE html> 
<html> 
<body> 

<form action="upload.php" method="post" enctype="multipart/form-data"> 
    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"><br> 
    <input type="submit" value="Upload Image" name="submit"> 
</form> 

</body> 
</html> 

Image Number 1

看圖像編號1,文件是越來越成功上傳。但是,當我點擊它,查看它,它顯示像圖像編號2

Image Number 2

回答

0

按照documentation請求(又名你CURLOPT_POSTFIELDS)的身體應該只包含[JPEG_DATA](又名只是你file_get_contents($uploadFile))。

但是在你的樣本中,你給了身體一個'fileName''fileData'的數組,這對於Google Cloud Storage JSON API甚至不是有效的body property metadata names

谷歌雲存儲然後解釋該數組的'fileName''fileData'作爲實際[JPEG_DATA],並呈現其作爲一個返回,你總能看到小正方形圖像的JPEG文件。

0

你的文件確實顯示在您的瀏覽器Image Number 2

由於圖像尺寸小,這是不易在您的瀏覽器顯示。在your uploaded image中,它顯示了一個有四個框(2個白色,2個灰色)的小白盒。您可以放大以確認。我相信那是你上傳的圖片。

您可以嘗試上傳尺寸稍大的不同圖像,並確認它是否正常工作。

+0

我嘗試上傳較大尺寸的圖片,但仍顯示相同 –