Reputation: 5
I am new to coding world.I want to upload a simple txt file to a bucket that is in my cloud storage. I didn't find any useful cloud documentations regarding it. here is the not working code:
<?php
require_once 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
define("PROJECT_ID", 'projectID');
define("BUCKET_NAME", 'bucketname');
$client = new Google_Client();
$client->setApplicationName("API_Cloud_Storage");
$client->useApplicationDefaultCredentials();
$client->setScopes(["https://www.googleapis.com/auth/cloud-platform"]);
$service = new Google_Service_Storage($client);
$request = $service->objects->listObjects(BUCKET_NAME);
foreach ($request["items"] as $object)
printf("%s\n", $object->getName());
printf("%s\n", $object->get);
$storage = new StorageClient();
$bucket = $storage->bucket(BUCKET_NAME); // Put your bucket name here.
$filePath="C:\users\useraccount\Desktop\address_file\textfile.txt";
$objectName="textfile.txt";
$object = $bucket->upload(file_get_contents($filePath),
['name' => $objectName]);
?>
Upvotes: 0
Views: 840
Reputation: 623
It seems that the issue is in your code and there is an answer provided in a related question that you can refer to (it also has a link to another useful documentation) that can help you correct your code [1]. You can also rely on this sample code in GitHub [2].
In terms of the concept of uploading a local file to later provide public access to write to it. I think you may need to read a bit more about serving files uploaded with your app from the filesystem [3]. I also advise that you read through this entire documentation as it talks about serving files from a script or directly from GCS [4].
[1] https://stackoverflow.com/a/48559967
[4] https://cloud.google.com/appengine/docs/standard/php/googlestorage/public_access#top_of_page
Upvotes: 1
Reputation: 623
Fortunately Google App Engine (GAE) provides a built-in Google Cloud Storage (GCS) stream wrapper that allows you to use many of the standard PHP filesystem functions to read and write files in an App Engine PHP app. I am also improving my coding skills and have found tips that worked for me in the GCP Documentation.
Taking from the code snippet you provided, you have to ensure you have done at least 2 things:
These are standard how-to guides (Tutorials are at the bottom of navigation bar) so make sure to view the examples provided on Github to take a look at the complete codes and adapt the style to yours.
Hope this helps!
[1] https://cloud.google.com/storage/docs/creating-buckets
[2] https://cloud.google.com/appengine/docs/standard/php/googlestorage/#top_of_page
[3] https://cloud.google.com/appengine/docs/standard/php/googlestorage/user_upload
Upvotes: 1