Как создать ссылку на Cloud Storage с помощью Cloud Storage для Unity

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

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

Создание ссылки

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

Ссылки создаются сервисом Firebase.Storage.FirebaseStorage в приложении Firebase с помощью метода GetReferenceFromUrl() и URL в формате gs://<your-cloud-storage-bucket>. Этот URL можно найти в разделе "Память" консоли Firebase.

// Get a reference to the storage service, using the default Firebase App
FirebaseStorage storage = FirebaseStorage.DefaultInstance;

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

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

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

// Child references can also take paths delimited by '/' such as:
// "images/space.jpg".
StorageReference spaceRef = imagesRef.Child("space.jpg");
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"

// This is equivalent to creating the full referenced
StorageReference spaceRefFull = 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
// imagesRef now points to 'images'
StorageReference imagesRef = spaceRef.Parent;

// Root allows us to move all the way back to the top of our bucket
// rootRef now points to the root
StorageReference rootRef = spaceRef.Root;

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

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

// nullRef is null since the parent of root is an invalid StorageReference
StorageReference nullRef = spaceRef.Root.Parent;

Методы сравнения

Чтобы лучше понять, на какие файлы указывают ссылки, можно использовать свойства Path, Name и Bucket. Эти свойства получают полный путь к файлу, его название и сегмент.

// Reference's path is: "images/space.jpg"
// This is analogous to a file path on disk
string path = spaceRef.Path;

// Reference's name is the last segment of the full path: "space.jpg"
// This is analogous to the file name
string name = spaceRef.Name;

// Reference's bucket is the name of the storage bucket where files are stored
string bucket = spaceRef.Bucket;

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

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

  1. Общая длина reference.Path должна составлять от 1 до 1024 байт в кодировке UTF-8.
  2. В них запрещены управляющие символы ASCII (CR и LF).
  3. Не используйте #, [, ], * или ?, поскольку эти символы плохо работают с другими инструментами, например Firebase Realtime Database или gsutil.

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

FirebaseStorage storage = FirebaseStorage.DefaultInstance;

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

// Points to "images"
StorageReference imagesRef = storageRef.Child("images");

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

// File path is "images/space.jpg"
string path = spaceRef.Path;

// File name is "space.jpg"
string name = spaceRef.Name;

// Points to "images"
StorageReference imagesRef = spaceRef.Parent;

Дальнейшие действия

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