Google 云平台 - 如何将图片文件上传到google 云存储桶?

Google Cloud Platform - How to upload image file into google cloud storage bucket?

我正在尝试使用 Google 云存储 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

您的文件确实显示在浏览器的 Image Number 2 中。

由于您的图片尺寸较小,因此在您的浏览器中不容易看到。在 your uploaded image 中,它显示了一个小白框,里面有四个框(2 个白色,2 个灰色)。您可以放大以确认。我相信那是你上传的图片。

您可以尝试上传尺寸稍大的不同图片并确认它是否有效。

根据 documentation 请求的正文(也就是您的 CURLOPT_POSTFIELDS)应该只包含 [JPEG_DATA](也就是您的 file_get_contents($uploadFile))。

但在您的示例中,您给正文提供了 'fileName''fileData' 的数组,它们甚至无效 body property metadata names for the Google Cloud Storage JSON API

Google Cloud Storage 然后将这个 'fileName''fileData' 的数组解释为实际的 [JPEG_DATA],并将其呈现为 returns 的 JPEG 文件正如您经常看到的小方形图像。