您的文件存储在Cloud Storage 存储分区中。此存储桶中的文件以分层结构呈现,就像本地硬盘上的文件系统或 Firebase 实时数据库中的数据一样。通过创建对文件的引用,您的应用程序可以访问它。然后,这些引用可用于上传或下载数据、获取或更新元数据或删除文件。引用可以指向特定文件或层次结构中的更高级别节点。
如果您使用过Firebase 实时数据库,这些路径对您来说应该非常熟悉。但是,您的文件数据存储在 Cloud Storage 中,而不是实时数据库中。
创建参考
创建引用以上传、下载或删除文件,或者获取或更新其元数据。可以将引用视为指向云中文件的指针。引用是轻量级的,因此您可以根据需要创建任意数量的引用。它们也可重复用于多个操作。
使用FirebaseStorage
单例实例创建引用并调用其ref()
方法。
final storageRef = FirebaseStorage.instance.ref();
接下来,您可以通过对现有引用使用child()
方法来创建对树中较低位置的引用,例如"images/space.jpg"
。
// Create a child reference
// imagesRef now points to "images"
final imagesRef = storageRef.child("images");
// Child references can also take paths
// spaceRef now points to "images/space.jpg
// imagesRef still points to "images"
final spaceRef = storageRef.child("images/space.jpg");
使用参考导航
您还可以使用parent
和root
属性在我们的文件层次结构中向上导航。 parent
向上导航一级,而root
一直导航到顶部。
// parent allows us to move our reference to a parent node
// imagesRef2 now points to 'images'
final imagesRef2 = spaceRef.parent;
// root allows us to move all the way back to the top of our bucket
// rootRef now points to the root
final rootRef = spaceRef.root;
child()
、 parent
和root
可以多次链接在一起,因为每个都是引用。但是访问root.parent
会导致null
。
// References can be chained together multiple times
// earthRef points to 'images/earth.jpg'
final earthRef = spaceRef.parent?.child("earth.jpg");
// nullRef is null, since the parent of root is null
final nullRef = spaceRef.root.parent;
参考属性
您可以使用fullPath
、 name
和bucket
属性检查引用以更好地理解它们指向的文件。这些属性获取文件的完整路径、名称和存储桶。
// Reference's path is: "images/space.jpg"
// This is analogous to a file path on disk
spaceRef.fullPath;
// Reference's name is the last segment of the full path: "space.jpg"
// This is analogous to the file name
spaceRef.name;
// Reference's bucket is the name of the storage bucket that the files are stored in
spaceRef.bucket;
参考文献的限制
引用路径和名称可以包含任何有效的 Unicode 字符序列,但有一些限制,包括:
- UTF-8 编码时,reference.fullPath 的总长度必须在 1 到 1024 个字节之间。
- 没有回车或换行字符。
- 避免使用
#
、[
、]
、*
或?
,因为这些不能很好地与Firebase 实时数据库或gsutil等其他工具配合使用。
完整示例
// Points to the root reference
final storageRef = FirebaseStorage.instance.ref();
// Points to "images"
Reference? imagesRef = storageRef.child("images");
// Points to "images/space.jpg"
// Note that you can use variables to create child values
final fileName = "space.jpg";
final spaceRef = imagesRef.child(fileName);
// File path is "images/space.jpg"
final path = spaceRef.fullPath;
// File name is "space.jpg"
final name = spaceRef.name;
// Points to "images"
imagesRef = spaceRef.parent;
接下来,让我们学习如何将文件上传到 Cloud Storage。