Создайте ссылку на облачное хранилище с помощью Cloud Storage для C++.

Your files are stored in a Cloud Storage bucket. The files in this bucket are presented in a hierarchical structure, just like the file system on your local hard disk, or the data in the Firebase Realtime Database . By creating a reference to a file, your app gains access to it. These references can then be used to upload or download data, get or update metadata or delete the file. A reference can either point to a specific file or to a higher level node in the hierarchy.

Если вы использовали Firebase Realtime Database , эти пути должны показаться вам очень знакомыми. Однако ваши файловые данные хранятся в Cloud Storage , а не в Realtime Database .

Создать ссылку

Создайте ссылку для загрузки, скачивания или удаления файла, а также для получения или обновления его метаданных. Ссылку можно рассматривать как указатель на файл в облаке. Ссылки являются легковесными, поэтому вы можете создать столько ссылок, сколько вам нужно. Они также могут быть использованы повторно для различных операций.

Ссылки создаются из службы storage в вашем приложении Firebase путем вызова метода GetReferenceFromUrl() и передачи URL-адреса вида gs://<your-cloud-storage-bucket> . Этот URL-адрес можно найти в разделе «Хранилище» консоли Firebase .

// Get a reference to the storage service, using the default Firebase App
Storage* storage = Storage::GetInstance(app);

// Create a Cloud Storage reference from our storage service
StorageReference storage_ref = storage->GetReferenceFromUrl("gs://<your-cloud-storage-bucket>");

Вы можете создать ссылку на местоположение, расположенное ниже в дереве, например, на 'images/space.jpg' , используя метод child для уже существующей ссылки.

// Create a child reference
// images_ref now points to "images"
StorageReference images_ref = storage_ref.Child("images");

// Child references can also take paths delimited by '/'
// space_ref now points to "images/space.jpg"
// images_ref still points to "images"
StorageReference space_ref = storage_ref.Child("images/space.jpg");

// This is equivalent to creating the full reference
StorageReference space_ref = storage.GetReferenceFromUrl("gs://<your-cloud-storage-bucket>/images/space.jpg");

Для навигации вверх по файловой иерархии можно также использовать методы Parent и Root . Parent перемещает на один уровень вверх, а Root — до самого верха.

// Parent allows us to move to the parent of a reference
// images_ref now points to 'images'
StorageReference images_ref = space_ref.Parent();

// Root allows us to move all the way back to the top of our bucket
// root_ref now points to the root
StorageReference root_ref = space_ref.Root();

Child , Parent и Root можно объединять в цепочку несколько раз, поскольку каждый из них возвращает ссылку. Исключением является объект Parent объекта Root , который является недопустимым StorageReference .

// References can be chained together multiple times
// earth_ref points to "images/earth.jpg"
StorageReference earth_ref = space_ref.Parent().Child("earth.jpg");

// null_ref is null, since the parent of root is an invalid StorageReference
StorageReference null_ref = space_ref.Root().Parent();

Референтные методы

Для лучшего понимания файлов, на которые они указывают, можно просмотреть ссылки, используя методы ` full_path , name и bucket . Эти методы позволяют получить полный путь к файлу, его имя и название корзины.

// Reference's path is: "images/space.jpg"
// This is analogous to a file path on disk
space_ref.full_path();

// Reference's name is the last segment of the full path: "space.jpg"
// This is analogous to the file name
space_ref.name();

// Reference's bucket is the name of the Cloud Storage bucket where files are stored
space_ref.bucket();

Ограничения на использование ссылок

Ссылочные пути и имена могут содержать любую последовательность допустимых символов Unicode, но на них накладываются определенные ограничения, в том числе:

  1. Общая длина reference.fullPath должна составлять от 1 до 1024 байт при кодировке UTF-8.
  2. Символы возврата каретки и перевода строки запрещены.
  3. Избегайте использования # , [ , ] , * или ? , поскольку они плохо работают с другими инструментами, такими как Firebase Realtime Database или gsutil .

Полный пример

Storage* storage = Storage::GetInstance(app);

// Points to the root reference
StorageReference storage_ref = storage->GetReferenceFromUrl("gs://<your-bucket-name>");

// Points to "images"
StorageReference images_ref = storage_ref.Child("images");

// Points to "images/space.jpg"
// Note that you can use variables to create child values
std::string filename = "space.jpg";
StorageReference space_ref = images_ref.Child(filename);

// File path is "images/space.jpg"
std::string path = space_ref.full_path()

// File name is "space.jpg"
std::string name = space_ref.name()

// Points to "images"
StorageReference images_ref = space_ref.Parent();

Следующие шаги

Далее давайте узнаем, как загружать файлы в Cloud Storage .