2017-07-18 156 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

我尝试上传较大尺寸的图片,但仍显示相同 –