Google Cloud Platform-如何将图像文件上传到Google Cloud Storage Bucket?

问题描述 投票:1回答:2

我正在尝试使用Google Cloud Storage JSON API将图像上传到Google Cloud Storage存储桶中。 该文件正在上传,但未显示任何内容。

<?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>

图片编号1

查看图像编号1,文件已成功上传。 但是,当我单击它进行查看时,它显示为图像编号2。

图片编号2

php google-cloud-platform google-cloud-storage json-api
2个回答
0
投票

您的文件确实显示在浏览器中的“ 图像编号2 ”中。

由于图像尺寸较小,因此在浏览器中不容易看到。 在您上传的图片中 ,它显示了一个白色小方框,其中包含四个方框(2个白色,2个灰色)。 您可以放大以确认。 我相信这就是您上传的图片。

您可以尝试上传尺寸稍大的其他图像,然后确认其是否正常工作。


0
投票

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

但是在您的示例中,您为主体提供了一个'fileName''fileData'数组,它们甚至都不是Google Cloud Storage JSON API的有效主体属性元数据名称

然后,Google Cloud Storage将'fileName''fileData'为实际的[JPEG_DATA] ,并将其呈现为JPEG文件,并返回为您经常看到的小正方形图像。

© www.soinside.com 2019 - 2024. All rights reserved.