如何使用php将文件上传到Google云存储中存储桶中的子文件夹

时间:2019-07-15 04:22:03

标签: php google-cloud-storage

我想将文件上传到存储桶中的子文件夹,我该怎么做,谁能帮助我做到这一点

我可以升级到存储桶,但无法上传到存储桶中的子文件夹

我的存储桶名称是fb-uploads

子文件夹是中国

下面是我的代码

<?php
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;

 $storage = new StorageClient([ 'keyFilePath' => 'facebooth_bucket.json']);
 $bucketName = 'fb-uploads';

$uploadDocument = isset($_FILES['uploaded_file']) ? $_FILES['uploaded_file'] : '';

$uploaddir = "uploads/";

if (isset($uploadDocument['name']) && !empty($uploadDocument['name'])) {

                $uploadFileName = str_replace(" ","_",basename($uploadDocument['name']));

                $ext = pathinfo($uploadFileName, PATHINFO_EXTENSION);
                $fileName = str_replace("." . $ext, "", $uploadFileName);


                $uploadFileName = $fileName . "_" . date('his') . '.' . $ext;

                $uploadfile = $uploaddir . $uploadFileName;
                // die($uploadfile);

                if (move_uploaded_file($uploadDocument['tmp_name'], $uploadfile)) {

                    if(file_exists($uploadfile)) {
                        try {
                                $objectName = $uploadFileName;

                                $file = fopen($uploadfile, 'r');
                                $bucket = $storage->bucket($bucketName);
                                $object = $bucket->upload('/china/'.$uploadfile, [
                                    'name' => $objectName
                                ]);
                                printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($uploadFileName), $bucketName, $objectName);
                            // require_once __DIR__ . "/google_storage/vendor/autoload.php";
                            // $storage = new StorageClient([
                            //     'keyFilePath' => '/var/www/html/crewbies/upload_testing/google_storage/key/facebooth_bucket.json'
                            // ]);
                            // $bucket =  $storage->bucket('fb-uploads');
                            // $bucket->upload(
                            //     fopen('/china/$uploadfile', 'r')
                            // );
                        }
                        catch(Exception $e) {
                            $err = $e->getMessage();
                            print_r($err);
                            die('heee');
                        }

                    }

                }


            }

            ?>


<html>
   <body>

      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="uploaded_file" />
         <input type="submit"/>
      </form>

   </body>
</html>

我想将文件上传到存储桶中的子文件夹,我该怎么做,谁能帮助我做到这一点

1 个答案:

答案 0 :(得分:0)

Documentation how subfolders work.

对象gs://your-bucket/abc/def.txt只是一个对象,其名称中恰好具有“ /”字符。

没有“ abc”目录;只是一个具有给定名称的对象。

我了解您的对象看起来像这样:

"/china/file-name.xxx"

但应为

"china/file-name.xxx"