公开数据

本页面介绍如何将您拥有的对象设为可供公共互联网上的所有人读取。如需了解如何访问已公开的数据,请参阅访问公开数据

将个别对象设为可供公开读取

如需将个别对象设为可供公共互联网上的所有人读取,请执行以下操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 检查访问权限控制列,确认是否存在包含您想要公开的对象的存储分区。如果该列显示精细控制,请继续执行下一步。如果该列显示统一,您就无法借助以下步骤将存储分区中的各个对象设为可供公开读取。而是授予对存储分区中所有对象的公开读取权限,或使用签名网址

  3. 点击您要公开的对象所在存储分区的名称,然后导航到该对象所在的位置(如果该对象位于子目录中)。

  4. 点击与您要公开的对象关联的更多操作菜单 ()。

  5. 从下拉菜单中选择修改权限。如果该选项不存在,您可能启用了统一访问权限控制。如需了解详情,请参阅第 2 步。

  6. 在出现的叠加窗口中,点击 + 添加条目按钮。

  7. 为 allUsers 添加权限。

    • 为“实体”选择公共
    • 为“名称”选择 allUsers
    • 为“访问权限”选择读取者
  8. 点击保存

对象被公开共享后,“公共访问权限”列中会显示一个链接图标。您可以点击此图标来获取对象的网址。

请参阅问题排查,了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息。

gsutil

使用 gsutil acl ch 命令:

gsutil acl ch -u AllUsers:R gs://BUCKET_NAME/OBJECT_NAME

其中:

  • BUCKET_NAME 是包含待公开对象的存储分区的名称。例如 my-bucket
  • OBJECT_NAME 是您要公开的对象的名称。例如 pets/dog.png

如果成功,则响应类似如下示例:

Updated ACL on gs://my-bucket/pets/dog.png

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name, gcs::ObjectMetadataPatchBuilder(),
      gcs::PredefinedAcl::PublicRead());

  if (!updated) throw std::runtime_error(updated.status().message());
  std::cout << "Object updated. The full metadata after the update is: "
            << *updated << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

private void MakePublic(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.Acl = storageObject.Acl ?? new List<ObjectAccessControl>();
    storage.UpdateObject(storageObject, new UpdateObjectOptions
    {
        PredefinedAcl = PredefinedObjectAcl.PublicRead
    });
    Console.WriteLine(objectName + " is now public and can be fetched from " +
        storageObject.MediaLink);
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

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

	"cloud.google.com/go/storage"
)

// makePublic gives all users read access to an object.
func makePublic(w io.Writer, bucket, object string, entity storage.ACLEntity, role storage.ACLRole) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

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

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %v", err)
	}
	fmt.Fprintf(w, "Blob %v is now publicly accessible.\n", object)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Acl;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class MakeObjectPublic {
  public static void makeObjectPublic(String projectId, String bucketName, String objectName) {
    // String projectId = "your-project-id";
    // String bucketName = "your-bucket-name";
    // String objectName = "your-object-name";
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    storage.createAcl(blobId, Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));

    System.out.println(
        "Object " + objectName + " in bucket " + bucketName + " was made publicly readable");
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to make public, e.g. file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function makePublic() {
  // Makes the file public
  await storage.bucket(bucketName).file(filename).makePublic();

  console.log(`gs://${bucketName}/${filename} is now public.`);
}

makePublic().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Make an object publically accessible.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function make_public($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
    printf('gs://%s/%s is now public' . PHP_EOL, $bucketName, $objectName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def make_blob_public(bucket_name, blob_name):
    """Makes a blob publicly accessible."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.make_public()

    print(
        "Blob {} is publicly accessible at {}".format(
            blob.name, blob.public_url
        )
    )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to make public"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.public!

puts "#{file.name} is publicly accessible at #{file.public_url}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "entity": "allUsers",
      "role": "READER"
    }
  3. 使用 cURL,通过 Insert ACL 请求调用 JSON API

    curl -X POST --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/acl"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中创建的访问令牌。
    • BUCKET_NAME 是包含待公开对象的存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是您要公开的对象的名称。例如 pets/dog.png

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .xml 文件:

    <AccessControlList>
      <Entries>
        <Entry>
          <Scope type="AllUsers"/>
          <Permission>READ</Permission>
        </Entry>
      </Entries>
    </AccessControlList>
  3. 使用 cURL,通过 Set Object ACL 请求调用 XML API

    curl -X PUT --data-binary @XML_FILE_NAME.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?acl"

    其中:

    • XML_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中创建的访问令牌。
    • BUCKET_NAME 是包含待公开对象的存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是您要公开的对象的名称。例如 pets/dog.png

将存储分区中的所有对象设为可供公开读取

如需将存储分区中的所有对象设为可供公共互联网上的所有人读取,请执行以下操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,点击要公开的存储分区的名称。

  3. 选择页面顶部附近的权限标签。

  4. 点击添加成员按钮。

    随即会显示“添加成员”对话框。

  5. 新成员字段中,输入 allUsers

  6. 选择角色下拉菜单中,选择 Cloud Storage 子菜单,然后点击 Storage Object Viewer 选项。

  7. 点击保存

对象群组被公开共享后,“公共访问权限”列中会针对每个对象显示一个链接图标。您可以点击此图标来获取对象的网址。

请参阅问题排查,了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息。

gsutil

使用 gsutil iam ch 命令:

gsutil iam ch allUsers:objectViewer gs://BUCKET_NAME

其中 BUCKET_NAME 是您要公开其对象的存储分区的名称。例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<google::cloud::IamPolicy> current_policy =
      client.GetBucketIamPolicy(bucket_name);

  if (!current_policy) {
    throw std::runtime_error(current_policy.status().message());
  }

  current_policy->bindings.AddMember("roles/storage.objectViewer",
                                     "allUsers");

  // Update the policy. Note the use of `gcs::IfMatchEtag` to implement
  // optimistic concurrency control.
  StatusOr<google::cloud::IamPolicy> updated_policy =
      client.SetBucketIamPolicy(bucket_name, *current_policy,
                                gcs::IfMatchEtag(current_policy->etag));

  if (!updated_policy) {
    throw std::runtime_error(current_policy.status().message());
  }

  auto role = updated_policy->bindings.find("roles/storage.objectViewer");
  if (role == updated_policy->bindings.end()) {
    std::cout << "Cannot find 'roles/storage.objectViewer' in the updated"
              << " policy. This can happen if another application updates"
              << " the IAM policy at the same time. Please retry the"
              << " operation.\n";
    return;
  }
  auto member = role->second.find("allUsers");
  if (member == role->second.end()) {
    std::cout << "'allUsers' is not a member of the"
              << " 'roles/storage.objectViewer' role in the updated"
              << " policy. This can happen if another application updates"
              << " the IAM policy at the same time. Please retry the"
              << " operation.\n";
    return;
  }
  std::cout << "IamPolicy successfully updated for bucket " << bucket_name
            << '\n';
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.StorageRoles;

public class MakeBucketPublic {
  public static void makeBucketPublic(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Policy originalPolicy = storage.getIamPolicy(bucketName);
    storage.setIamPolicy(
        bucketName,
        originalPolicy
            .toBuilder()
            .addIdentity(StorageRoles.objectViewer(), Identity.allUsers()) // All users can view
            .build());

    System.out.println("Bucket " + bucketName + " is now publicly readable");
  }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def set_bucket_public_iam(bucket_name, role, member):
    """Set a public IAM Policy to bucket"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g. roles/storage.objectViewer"
    # member = "IAM identity, e.g. allUsers"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)
    policy.bindings.append({"role": role, "members": {member}})

    bucket.set_iam_policy(policy)

    print("Bucket {} is now publicly readable".format(bucket.name))

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  3. 使用 cURL,通过 PUT Bucket 请求调用 JSON API

    curl -X PUT --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中创建的访问令牌。
    • BUCKET_NAME 是您要公开其对象的存储分区的名称。例如 my-bucket

XML API

XML API 不支持将存储分区中的所有对象设为可供公开读取。请改用 gsutil 或 JSON API。

后续步骤