יצירה וניהול של תיקיות

בדף הזה מוסבר איך ליצור, להציג רשימה, להעלות, למחוק ולקבל את המטא-נתונים של תיקיות בקטגוריות שבהן מופעל מרחב שמות היררכי.

לפני שמתחילים

מוודאים שהאפשרות 'מרחב שמות היררכי' מופעלת בדלי. הוראות מפורטות להפעלת מרחב שמות היררכי בקטגוריה זמינות במאמר יצירת קטגוריות עם מרחב שמות היררכי מופעל.

יצירת תיקייה

בקטע הזה מוסבר איך ליצור תיקייה.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שבה רוצים ליצור את התיקייה.
  3. בדף Bucket details, לוחצים על Create folder כדי ליצור תיקייה ריקה.
  4. בשדה שם, מזינים שם לתיקייה. לשיקולים בנוגע למתן שמות, ראו שיקולים.
  5. לוחצים על יצירה.

    התיקייה החדשה שנוצרה מופיעה בחלונית סייר התיקיות.

שורת הפקודה

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. בסביבת הפיתוח, מריצים את הפקודה gcloud storage folders create:

    gcloud storage folders create --recursive gs://BUCKET_NAME/FOLDER_NAME

    כאשר:

    • BUCKET_NAME הוא שם הקטגוריה. לדוגמה, my-bucket.
    • FOLDER_NAME הוא שם התיקייה שרוצים ליצור. לדוגמה, my-folder/. מידע על שמות של תיקיות זמין בסקירה הכללית על תיקיות.
    • --recursive הוא דגל שיוצר באופן אוטומטי את כל התיקיות הראשיות שלא קיימות, יחד עם התיקייה. ההגדרה הזו היא אופציונלית אם כבר קיימות תיקיות הורה.

    אם הבקשה מבוצעת בהצלחה, הפקודה תחזיר את ההודעה הבאה:

    Completed 1/1
  3. ספריות לקוח

    C++

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    namespace storagecontrol = google::cloud::storagecontrol_v2;
    [](storagecontrol::StorageControlClient client,
       std::string const& bucket_name, std::string const& folder_id) {
      auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
      auto folder = client.CreateFolder(
          parent, google::storage::control::v2::Folder{}, folder_id);
      if (!folder) throw std::move(folder).status();
    
      std::cout << "Created folder: " << folder->name() << "\n";
    }

    C#

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    using Google.Cloud.Storage.Control.V2;
    using System;
    
    public class StorageControlCreateFolderSample
    {
        public Folder StorageControlCreateFolder(string bucketName = "your-unique-bucket-name",
            string folderName = "your_folder_name")
        {
            StorageControlClient storageControl = StorageControlClient.Create();
    
            var request = new CreateFolderRequest
            {
                // Set project to "_" to signify globally scoped bucket
                Parent = BucketName.FormatProjectBucket("_", bucketName),
                FolderId = folderName
            };
    
            Folder folder = storageControl.CreateFolder(request);
    
            Console.WriteLine($"Folder {folderName} created in bucket {bucketName}");
            return folder;
        }
    }

    Go

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	control "cloud.google.com/go/storage/control/apiv2"
    	"cloud.google.com/go/storage/control/apiv2/controlpb"
    )
    
    // createFolder creates a folder in the bucket with the given name.
    func createFolder(w io.Writer, bucket, folder string) error {
    	// bucket := "bucket-name"
    	// folder := "folder-name"
    
    	ctx := context.Background()
    	client, err := control.NewStorageControlClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewStorageControlClient: %w", err)
    	}
    	defer client.Close()
    
    	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
    	defer cancel()
    
    	req := &controlpb.CreateFolderRequest{
    		Parent:   fmt.Sprintf("projects/_/buckets/%v", bucket),
    		FolderId: folder,
    	}
    	f, err := client.CreateFolder(ctx, req)
    	if err != nil {
    		return fmt.Errorf("CreateFolder(%q): %w", folder, err)
    	}
    
    	fmt.Fprintf(w, "created folder with path %q", f.Name)
    	return nil
    }
    

    Java

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    import com.google.storage.control.v2.BucketName;
    import com.google.storage.control.v2.CreateFolderRequest;
    import com.google.storage.control.v2.Folder;
    import com.google.storage.control.v2.StorageControlClient;
    import java.io.IOException;
    
    public final class CreateFolder {
    
      public static void createFolder(String bucketName, String folderName) throws IOException {
        // The name of the bucket
        // String bucketName = "your-unique-bucket-name";
    
        // The name of the folder within the bucket
        // String folderName = "your-unique-folder-name";
    
        try (StorageControlClient storageControl = StorageControlClient.create()) {
    
          CreateFolderRequest request =
              CreateFolderRequest.newBuilder()
                  // Set project to "_" to signify globally scoped bucket
                  .setParent(BucketName.format("_", bucketName))
                  .setFolderId(folderName)
                  .build();
    
          Folder newFolder = storageControl.createFolder(request);
    
          System.out.printf("Created folder: %s%n", newFolder.getName());
        }
      }
    }

    Node.js

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    
    // The name of your GCS bucket
    // const bucketName = 'bucketName';
    
    // The name of the folder to be created
    // const folderName = 'folderName';
    
    // Imports the Control library
    const {StorageControlClient} = require('@google-cloud/storage-control').v2;
    
    // Instantiates a client
    const controlClient = new StorageControlClient();
    
    async function callCreateFolder() {
      const bucketPath = controlClient.bucketPath('_', bucketName);
    
      // Create the request
      const request = {
        parent: bucketPath,
        folderId: folderName,
      };
    
      // Run request
      const [response] = await controlClient.createFolder(request);
      console.log(`Created folder: ${response.name}.`);
    }
    
    callCreateFolder();

    PHP

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
    use Google\Cloud\Storage\Control\V2\CreateFolderRequest;
    
    /**
     * Create a new folder in an existing bucket.
     *
     * @param string $bucketName The name of your Cloud Storage bucket.
     *        (e.g. 'my-bucket')
     * @param string $folderName The name of your folder inside the bucket.
     *        (e.g. 'my-folder')
     */
    function create_folder(string $bucketName, string $folderName): void
    {
        $storageControlClient = new StorageControlClient();
    
        // Set project to "_" to signify global bucket
        $formattedName = $storageControlClient->bucketName('_', $bucketName);
    
        $request = new CreateFolderRequest([
            'parent' => $formattedName,
            'folder_id' => $folderName,
        ]);
    
        $folder = $storageControlClient->createFolder($request);
    
        printf('Created folder: %s', $folder->getName());
    }

    Python

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    from google.cloud import storage_control_v2
    
    
    def create_folder(bucket_name: str, folder_name: str) -> None:
        # The ID of your GCS bucket
        # bucket_name = "your-unique-bucket-name"
    
        # The name of the folder to be created
        # folder_name = "folder-name"
    
        storage_control_client = storage_control_v2.StorageControlClient()
        # The storage bucket path uses the global access pattern, in which the "_"
        # denotes this bucket exists in the global namespace.
        project_path = storage_control_client.common_project_path("_")
        bucket_path = f"{project_path}/buckets/{bucket_name}"
    
        request = storage_control_v2.CreateFolderRequest(
            parent=bucket_path,
            folder_id=folder_name,
        )
        response = storage_control_client.create_folder(request=request)
    
        print(f"Created folder: {response.name}")
    
    

    Ruby

    למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

    כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

    def create_folder bucket_name:, folder_name:
      # The ID of your GCS bucket
      # bucket_name = "your-unique-bucket-name"
    
      # The name of the folder to be created
      # folder_name = "folder-name"
    
      require "google/cloud/storage/control"
    
      storage_control = Google::Cloud::Storage::Control.storage_control
    
      # The storage bucket path uses the global access pattern, in which the "_"
      # denotes this bucket exists in the global namespace.
      bucket_path = storage_control.bucket_path project: "_", bucket: bucket_name
    
      request = Google::Cloud::Storage::Control::V2::CreateFolderRequest.new parent: bucket_path, folder_id: folder_name
    
      response = storage_control.create_folder request
    
      puts "Created folder: #{response.name}"
    end

    ממשקי API ל-REST

    API ל-JSON

    1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

    2. יוצרים קובץ JSON עם ההגדרות של התיקייה, שחייבות לכלול name לתיקייה. רשימה מלאה של ההגדרות מופיעה במאמרי העזרה של Folders: Insert. אלו הגדרות החובה שצריך לכלול:
      {
        "name": "FOLDER_NAME",
      }

      כאשר FOLDER_NAME הוא שם התיקייה שרוצים ליצור. לדוגמה, my-folder/. מידע על שמות של תיקיות זמין בסקירה הכללית על תיקיות.

    3. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט JSON:
      curl -X POST --data-binary @JSON_FILE_NAME \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders?recursive=true"

      כאשר:

      • JSON_FILE_NAME הוא השם של קובץ ה-JSON שמכיל את ההגדרות של התיקייה.
      • BUCKET_NAME הוא שם הקטגוריה שבה רוצים ליצור את התיקייה.
      • הערך של recursive מוגדר כ-true כדי ליצור אוטומטית את כל התיקיות הראשיות שלא קיימות, יחד עם התיקייה. ההגדרה הזו היא אופציונלית אם כבר קיימות תיקיות הורה.

הצגת רשימה של תיקיות

בקטע הזה מוסבר איך מציגים רשימה של תיקיות.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על השם של הקטגוריה שרוצים להציג את התיקיות שלה.

  3. בחלונית Folder browser (דפדפן התיקיות), משתמשים בחץ ההרחבה כדי להרחיב את רשימת התיקיות בקטגוריה.

    רשימה שבה מוצגות התיקיות, התיקיות המדומות והתיקיות המנוהלות בדלי.

שורת הפקודה

כדי לראות את כל התיקיות בקטגוריה, מריצים את הפקודה gcloud storage folders list:

gcloud storage folders list gs://BUCKET_NAME/

כאשר:

  • BUCKET_NAME הוא שם הקטגוריה שמכילה את התיקיות שרוצים להציג ברשימה. לדוגמה, my-bucket.

תגובה מוצלחת נראית כך:

bucket: hns-bucket
id: hns-bucket/A/
kind: storage#folder
name: A/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/A
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/B/
kind: storage#folder
name: B/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/B/D/
kind: storage#folder
name: D/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B/D
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/C/
kind: storage#folder
name: C/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/C/E/
kind: storage#folder
name: E/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C/E
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
...

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  for (auto folder : client.ListFolders(parent)) {
    if (!folder) throw std::move(folder).status();
    std::cout << folder->name() << "\n";
  }

  std::cout << bucket_name << std::endl;
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

using Google.Cloud.Storage.Control.V2;
using System;
using System.Collections.Generic;

public class StorageControlListFoldersSample
{
    public IEnumerable<Folder> StorageControlListFolders(string bucketName = "your-unique-bucket-name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        // Use "_" for project ID to signify globally scoped bucket
        string bucketResourceName = BucketName.FormatProjectBucket("_", bucketName);
        var folders = storageControl.ListFolders(bucketResourceName);

        foreach (var folder in folders)
        {
            Console.Write(folder.Name);
        }
        return folders;
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
	"google.golang.org/api/iterator"
)

// listFolders lists all folders present in the bucket.
func listFolders(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct bucket path for a bucket containing folders.
	bucketPath := fmt.Sprintf("projects/_/buckets/%v", bucket)

	// List all folders present.
	req := &controlpb.ListFoldersRequest{
		Parent: bucketPath,
	}
	it := client.ListFolders(ctx, req)
	for {
		f, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListFolders(%q): %w", bucketPath, err)
		}
		fmt.Fprintf(w, "got folder %v\n", f.Name)
	}

	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.ListFoldersRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class ListFolders {

  public static void listFolders(String bucketName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      ListFoldersRequest request =
          ListFoldersRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setParent(BucketName.format("_", bucketName))
              .build();

      Iterable<Folder> folders = storageControl.listFolders(request).iterateAll();
      for (Folder folder : folders) {
        System.out.printf("Found folder: %s%n", folder.getName());
      }
    }
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callListFolders() {
  const bucketPath = controlClient.bucketPath('_', bucketName);

  // Create the request
  const request = {
    parent: bucketPath,
  };

  // Run request
  const [folders] = await controlClient.listFolders(request);
  for (const curFolder of folders) {
    console.log(curFolder.name);
  }
}

callListFolders();

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\ListFoldersRequest;

/**
 * List folders in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_folders(string $bucketName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->bucketName('_', $bucketName);

    $request = new ListFoldersRequest([
        'parent' => $formattedName,
    ]);

    $folders = $storageControlClient->listFolders($request);

    foreach ($folders as $folder) {
        printf('Folder name: %s' . PHP_EOL, $folder->getName());
    }
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from google.cloud import storage_control_v2


def list_folders(bucket_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    project_path = storage_control_client.common_project_path("_")
    bucket_path = f"{project_path}/buckets/{bucket_name}"

    request = storage_control_v2.ListFoldersRequest(
        parent=bucket_path,
    )

    page_result = storage_control_client.list_folders(request=request)
    for folder in page_result:
        print(folder)

    print(f"Listed folders in bucket {bucket_name}")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

def list_folders bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage bucket path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  bucket_path = storage_control.bucket_path project: "_", bucket: bucket_name

  request = Google::Cloud::Storage::Control::V2::ListFoldersRequest.new parent: bucket_path

  response = storage_control.list_folders request

  puts response.response.folders
end

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים בפקודה cURL כדי להעביר ל-API בפורמט JSON בקשה לקריאת רשימה של תיקיות:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders"

    כאשר BUCKET_NAME הוא שם הקטגוריה שמכילה את התיקיות שרוצים להציג ברשימה. לדוגמה, my-bucket.

העלאת תיקייה

בקטע הזה מוסבר איך מעלים תיקיות לקטגוריה.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שאליה רוצים להעלות את התיקייה.

  3. בכרטיסייה פרטי הקטגוריה, מבצעים אחת מהפעולות הבאות:

    • גוררים תיקיות משולחן העבודה או ממנהל הקבצים ומשחררים אותן בחלונית הראשית של Google Cloud המסוף.

    • לוחצים על העלאה > העלאת תיקייה, בוחרים את התיקייה שרוצים להעלות בתיבת הדו-שיח שמופיעה ולוחצים על פתיחה.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בפקודה gcloud storage cp עם הדגל --recursive:

gcloud storage cp --recursive FOLDER_LOCATION gs://DESTINATION_BUCKET_NAME

כאשר:

  • FOLDER_LOCATION הוא הנתיב המקומי לתיקייה שרוצים להעלות. לדוגמה, ../uploads/my-folder/.

  • DESTINATION_BUCKET_NAME הוא שם הקטגוריה שאליה מעלים את התיקייה. לדוגמה, my-bucket.

אם הפעולה בוצעה ללא שגיאות, התשובה תיראה כמו בדוגמה הבאה:

Copying file://DIR/OBJ1 at 10.06.32 PM.png to gs://BUCKET_NAME/DIR/OBJ1 at 10.06.32 PM.png
Copying file://DIR/OBJ1 at 10.06.32 PM.png to gs://BUCKET_NAME/DIR/OBJ1 at 10.06.32 PM.png
Completed files 2/2 | 1.7MiB/1.7MiB

מחיקת תיקייה

בקטע הזה מוסבר איך למחוק תיקיות.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שמכילה את התיקיות שרוצים למחוק.

  3. בחלונית Folder browser (דפדפן התיקיות), משתמשים בחץ ההרחבה כדי להרחיב את רשימת התיקיות בקטגוריה.

  4. מאתרים את התיקייה שרוצים למחוק.

  5. לוחצים על סמל האפשרויות הנוספות של התיקייה.

  6. לוחצים על מחיקת התיקייה.

  7. כדי לאשר את מחיקת התיקייה, מקלידים DELETE בשדה מחיקה.

  8. לוחצים על Delete.

    התיקייה והתוכן שלה, כולל אובייקטים מאוחסנים ותיקיות מנוהלות אחרות, נמחקים מהקטגוריה שלכם ב-Cloud Storage.

שורת הפקודה

כדי למחוק תיקייה ריקה, מריצים את הפקודה gcloud storage folders delete:

gcloud storage folders delete gs://BUCKET_NAME/FOLDER_NAME

כאשר:

  • BUCKET_NAME הוא שם הקטגוריה. לדוגמה, my-bucket.

  • FOLDER_NAME הוא השם של התיקייה שרוצים למחוק. לדוגמה, my-folder/.

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/folders/" + folder_id;
  auto status = client.DeleteFolder(name);
  if (!status.ok()) throw std::move(status);

  std::cout << "Deleted folder: " << folder_id << "\n";
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlDeleteFolderSample
{
    public void StorageControlDeleteFolder(string bucketName = "your-unique-bucket-name",
        string folderName = "your_folder_name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        string folderResourceName =
            // Set project to "_" to signify globally scoped bucket
            FolderName.FormatProjectBucketFolder("_", bucketName, folderName);

        storageControl.DeleteFolder(folderResourceName);

        Console.WriteLine($"Deleted folder {folderName} from bucket {bucketName}");
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// deleteFolder deletes the folder with the given name.
func deleteFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct folder path including the bucket name.
	folderPath := fmt.Sprintf("projects/_/buckets/%v/folders/%v", bucket, folder)

	req := &controlpb.DeleteFolderRequest{
		Name: folderPath,
	}
	if err := client.DeleteFolder(ctx, req); err != nil {
		return fmt.Errorf("DeleteFolder(%q): %w", folderPath, err)
	}

	fmt.Fprintf(w, "deleted folder %q", folderPath)
	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.storage.control.v2.DeleteFolderRequest;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class DeleteFolder {

  public static void deleteFolder(String bucketName, String folderName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the folder within the bucket
    // String folderName = "your-unique-folder-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      // Set project to "_" to signify globally scoped bucket
      String folderResourceName = FolderName.format("_", bucketName, folderName);
      DeleteFolderRequest request =
          DeleteFolderRequest.newBuilder().setName(folderResourceName).build();

      storageControl.deleteFolder(request);

      System.out.printf("Deleted folder: %s%n", folderResourceName);
    }
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The name of the folder to be deleted
// const folderName = 'folderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callDeleteFolder() {
  const folderPath = controlClient.folderPath('_', bucketName, folderName);

  // Create the request
  const request = {
    name: folderPath,
  };

  // Run request
  await controlClient.deleteFolder(request);
  console.log(`Deleted folder: ${folderName}.`);
}

callDeleteFolder();

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\DeleteFolderRequest;

/**
 * Delete a folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $folderName The name of your folder inside the bucket.
 *        (e.g. 'my-folder')
 */
function delete_folder(string $bucketName, string $folderName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->folderName('_', $bucketName, $folderName);

    $request = new DeleteFolderRequest([
        'name' => $formattedName,
    ]);

    $storageControlClient->deleteFolder($request);

    printf('Deleted folder: %s', $folderName);
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from google.cloud import storage_control_v2


def delete_folder(bucket_name: str, folder_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    # The name of the folder to be deleted
    # folder_name = "folder-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    folder_path = storage_control_client.folder_path(
        project="_", bucket=bucket_name, folder=folder_name
    )

    request = storage_control_v2.DeleteFolderRequest(
        name=folder_path,
    )
    storage_control_client.delete_folder(request=request)

    print(f"Deleted folder {folder_name}")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

def delete_folder bucket_name:, folder_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"
  #
  # Name of the folder you want to delete
  # folder_name = "name-of-the-folder"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage folder path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  folder_path = storage_control.folder_path project: "_", bucket: bucket_name, folder: folder_name

  request = Google::Cloud::Storage::Control::V2::DeleteFolderRequest.new name: folder_path

  storage_control.delete_folder request

  puts "Deleted folder: #{folder_name}"
end

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של DELETE תיקייה:

    curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders/FOLDER_NAME"

    כאשר:

    • BUCKET_NAME הוא שם הקטגוריה שמכילה את התיקייה שרוצים למחוק. לדוגמה, my-bucket.

    • FOLDER_NAME הוא השם של התיקייה שרוצים למחוק, בקידודי תווים שמתאימים לכתובות URL. לדוגמה, my-folder/ יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: my-folder%2F.

אחזור המטא-נתונים של תיקייה

בקטע הזה מוסבר איך לאחזר את המטא-נתונים של תיקייה.

שורת הפקודה

כדי לקבל את המטא-נתונים של תיקייה, מריצים את הפקודה gcloud storage folders describe:

gcloud storage folders describe gs://BUCKET_NAME/FOLDER_NAME

כאשר:

  • BUCKET_NAME הוא שם הקטגוריה שמכילה את התיקייה שרוצים לאחזר את המטא-נתונים שלה. לדוגמה, my-bucket.
  • FOLDER_NAME הוא שם התיקייה שרוצים לאחזר את המטא-נתונים שלה. לדוגמה, my-folder/.

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/folders/" + folder_id;
  auto folder = client.GetFolder(name);
  if (!folder) throw std::move(folder).status();

  std::cout << "Got folder: " << folder->name() << "\n";
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlGetFolderSample
{
    public Folder StorageControlGetFolder(string bucketName = "your-unique-bucket-name",
        string folderName = "your_folder_name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        string folderResourceName =
            // Set project to "_" to signify globally scoped bucket
            FolderName.FormatProjectBucketFolder("_", bucketName, folderName);

        Folder folder = storageControl.GetFolder(folderResourceName);

        Console.WriteLine($"Got folder: {folder.Name}");
        return folder;
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// getFolder gets metadata for the folder with the given name.
func getFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct folder path including the bucket name.
	folderPath := fmt.Sprintf("projects/_/buckets/%v/folders/%v", bucket, folder)

	req := &controlpb.GetFolderRequest{
		Name: folderPath,
	}
	f, err := client.GetFolder(ctx, req)
	if err != nil {
		return fmt.Errorf("GetFolder(%q): %w", folderPath, err)
	}

	fmt.Fprintf(w, "got folder metadata: %+v", f)
	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.GetFolderRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class GetFolder {

  public static void getFolder(String bucketName, String folderName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the folder within the bucket
    // String folderName = "your-unique-folder-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      GetFolderRequest request =
          GetFolderRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setName(FolderName.format("_", bucketName, folderName))
              .build();

      Folder newFolder = storageControl.getFolder(request);

      System.out.printf("Got folder: %s%n", newFolder.getName());
    }
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The name of the folder to get
// const folderName = 'folderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callGetFolder() {
  const folderPath = controlClient.folderPath('_', bucketName, folderName);

  // Create the request
  const request = {
    name: folderPath,
  };

  // Run request
  const [response] = await controlClient.getFolder(request);
  console.log(`Got folder: ${response.name}.`);
}

callGetFolder();

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\GetFolderRequest;

/**
 * Get a folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $folderName The name of your folder inside the bucket.
 *        (e.g. 'my-folder')
 */
function get_folder(string $bucketName, string $folderName): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->folderName('_', $bucketName, $folderName);

    $request = new GetFolderRequest([
        'name' => $formattedName,
    ]);

    $folder = $storageControlClient->getFolder($request);

    printf($folder->getName());
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from google.cloud import storage_control_v2


def get_folder(bucket_name: str, folder_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    # The name of the folder
    # folder_name = "folder-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage bucket path uses the global access pattern, in which the "_"
    # denotes this bucket exists in the global namespace.
    folder_path = storage_control_client.folder_path(
        project="_", bucket=bucket_name, folder=folder_name
    )

    request = storage_control_v2.GetFolderRequest(
        name=folder_path,
    )
    response = storage_control_client.get_folder(request=request)

    print(f"Got folder: {response.name}")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

def get_folder bucket_name:, folder_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of the folder to be created
  # folder_name = "folder-name"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage folder path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  folder_path = storage_control.folder_path project: "_", bucket: bucket_name, folder: folder_name

  request = Google::Cloud::Storage::Control::V2::GetFolderRequest.new name: folder_path

  response = storage_control.get_folder request

  puts "Got folder #{response.name}"
end

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשת GETתיקייה:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders/FOLDER_NAME"

    כאשר:

    • BUCKET_NAME הוא שם הקטגוריה שמכילה את התיקייה שרוצים לאחזר את המטא-נתונים שלה. לדוגמה, my-bucket.

    • FOLDER_NAME הוא השם של התיקייה שרוצים לאחזר את המטא-נתונים שלה, בקידודי תווים שמתאימים לכתובות URL. לדוגמה, my-folder/ יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: my-folder%2F.

ניהול הגישה לתיקייה

בקטע הזה מוסבר איך לנהל את הגישה לתיקייה באמצעות הגדרת כללי מדיניות של ניהול זהויות והרשאות גישה (IAM), כדי לקבל שליטה מדויקת בהרשאות הגישה לקבוצות ספציפיות של אובייקטים בתוך קטגוריה.

כדי לנהל את הגישה לתיקייה:

  1. כדי להפעיל את הניהול בתיקייה, יוצרים תיקייה מנוהלת עם אותו שם כמו של התיקייה הקיימת. הוראות מפורטות זמינות במאמר בנושא יצירת תיקייה מנוהלת.

  2. הגדרה וניהול של מדיניות ניהול זהויות והרשאות גישה (IAM) בתיקייה המנוהלת שיצרתם.

המאמרים הבאים

נסו בעצמכם

אנחנו ממליצים למשתמשים חדשים ב-Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של Cloud Storage בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300 $להרצה, לבדיקה ולפריסה של עומסי העבודה.

להתנסות ב-Cloud Storage בחינם