您的文件存儲在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。