使用 Cloud Storage

您可以使用 Cloud Storage 来存储和提供文件,例如电影、图片或其他静态内容。

本文档介绍了如何在应用中使用 Google Cloud 客户端库将数据存储在 Cloud Storage 中,以及如何从 Cloud Storage 检索数据。

准备工作

  • 请按照 App Engine .NET 版“Hello, World!”中的说明设置您的环境和项目,并了解如何在 App Engine 中设计 .NET 应用的结构。请记录并保存项目 ID,因为您需要用它来运行本文档中介绍的示例应用。

  • 请务必调用以下命令,为您的应用创建 Cloud Storage 存储分区:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 将此存储分区设为可公开读取,以便其可以传送文件:

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    
  • 要在本地运行您的应用,请设置服务帐号并下载凭据:

    1. 在 Google Cloud Console 中打开凭据列表。

      打开凭据列表

    2. 点击创建凭据

    3. 选择服务帐号密钥

      此时会打开“创建服务帐号密钥”窗口。

    4. 点击“服务帐号”下方的下拉框,然后点击 Compute Engine 默认服务帐号

    5. 选择 JSON 作为密钥类型

    6. 点击创建

      此时,系统会显示新建私钥窗口,并自动下载与您所选密钥类型相对应的私钥。

    7. 点击关闭

    8. 将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为下载的 JSON 密钥的路径。例如,在 PowerShell 中使用以下命令:

      # For this powershell session.
      PS > $env:GOOGLE_APPLICATION_CREDENTIALS = "$env:USERPROFILE\Downloads\your-project-id-dea9fa230eae3.json"
      # For all processes created after this command.
      PS > [Environment]::SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "$env:USERPROFILE\Downloads\your-project-id-dea9fa230eae3.json", "User")
      

下载示例

  1. 下载示例应用并将其解压缩。

  2. 如果您使用的是命令行,请导航到应用目录“dotnet-docs-samples\appengine\flexible”。

修改项目配置并安装依赖项

appsettings.json 中设置 BucketName;此值是您之前创建的 Cloud Storage 存储分区的名称。

{
  "GoogleCloudStorage": {
    "BucketName": "your-google-bucket-name"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

应用代码

示例应用会显示一个网页,提示用户选择要存储在 Cloud Storage 中的文件。用户选择文件并点击“提交”后,上传处理程序会将文件内容加载到 Blob 中并将其写入 Cloud Storage。

请注意,在文件上传到 Cloud Storage 后,系统会返回该文件的公共网址,您可以使用该网址直接从 Cloud Storage 传送该文件。您应将此值存储在应用中以备将来使用。

    public class HomeController : Controller
    {
        // Contains the bucket name and object name
        readonly CloudStorageOptions _options;
        // The Google Cloud Storage client.
        readonly StorageClient _storage;

        public HomeController(IOptions<CloudStorageOptions> options)
        {
            _options = options.Value;
            _storage = StorageClient.Create();
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var model = new HomeIndex();
            if (new string[] { null, "", "your-google-bucket-name" }
                .Contains(_options.BucketName))
            {
                model.MissingBucketName = true;
                return View(model);
            }
            try
            {
                // Get the storage object.
                var storageObject =
                    await _storage.GetObjectAsync(_options.BucketName, _options.ObjectName);
                // Get a direct link to the storage object.
                model.MediaLink = storageObject.MediaLink;
                // Download the storage object.
                MemoryStream m = new MemoryStream();
                await _storage.DownloadObjectAsync(
                    _options.BucketName, _options.ObjectName, m);
                m.Seek(0, SeekOrigin.Begin);
                byte[] content = new byte[m.Length];
                m.Read(content, 0, content.Length);
                model.Content = Encoding.UTF8.GetString(content);
            }
            catch (GoogleApiException e)
            when (e.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
            {
                // Does not exist yet.  No problem.
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Index(Form sendForm)
        {
            var model = new HomeIndex();
            // Take the content uploaded in the form and upload it to
            // Google Cloud Storage.
            await _storage.UploadObjectAsync(
                _options.BucketName, _options.ObjectName, "text/plain",
                new MemoryStream(Encoding.UTF8.GetBytes(sendForm.Content)));
            model.Content = sendForm.Content;
            model.SavedNewContent = true;
            var storageObject =
                await _storage.GetObjectAsync(_options.BucketName, _options.ObjectName);
            model.MediaLink = storageObject.MediaLink;
            return View(model);
        }

了解详情

如需全面了解 Cloud Storage,请参阅 Cloud Storage 文档