Cloud Storage 사용

Cloud Storage를 사용하여 영화, 이미지 또는 기타 정적 콘텐츠와 같은 파일을 저장하고 제공할 수 있습니다.

이 문서는 앱에서 Google Cloud 클라이언트 라이브러리를 사용하여 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에 업로드된 후에는 이 파일의 공개 URL이 반환되며, 이 URL을 사용하여 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 문서를 참조하세요.