I am trying to upload Image into google cloud storage bucket using Google Cloud Storage JSON API. The file is getting uploaded but it is not showing anything.
<?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;
}
}
?>
I am uploading image through this:-
<!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>
Look at the image number 1, the file is getting uploaded successfully. But when I click on it to view it, it shows like in image number 2.
According to the documentation the body of the request (aka your CURLOPT_POSTFIELDS
) should only contain the [JPEG_DATA]
(aka just your file_get_contents($uploadFile)
).
But in your sample, you are giving the body an array of 'fileName'
and 'fileData'
which are not even valid body property metadata names for the Google Cloud Storage JSON API.
Google Cloud Storage then interprets this array of 'fileName'
and 'fileData'
as the actual [JPEG_DATA]
, and renders it as a JPEG file that returns as the small square image you always see.