ファイルはCloudStorageバケットに保存されます。このバケット内のファイルは、ローカルハードディスク上のファイルシステムやFirebase Realtime Database内のデータと同様に、階層構造で表示されます。ファイルへの参照を作成することで、アプリはそのファイルにアクセスできるようになります。これらの参照を使用して、データのアップロードまたはダウンロード、メタデータの取得または更新、またはファイルの削除を行うことができます。参照は、特定のファイルまたは階層内のより高いレベルのノードを指すことができます。
Firebase Realtime Databaseを使用したことがある場合、これらのパスは非常に馴染みがあるように思われるはずです。ただし、ファイルデータはRealtimeDatabaseではなくCloudStorageに保存されます。
参照を作成する
ファイルをアップロード、ダウンロード、または削除するため、またはそのメタデータを取得または更新するための参照を作成します。参照は、クラウド内のファイルへのポインターと考えることができます。参照は軽量であるため、必要な数だけ作成できます。また、複数の操作に再利用できます。
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
は1レベル上に移動し、 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バイトである必要があります。
- キャリッジリターンまたはラインフィード文字はありません。
-
#
、[
、]
、*
、または?
の使用は避けてください、 FirebaseRealtimeDatabaseや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;
次に、ファイルをクラウドストレージにアップロードする方法を学びましょう。