Flutter에서 Cloud Storage 참조 만들기

파일은 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");

parentroot 속성을 사용하여 파일 계층에서 상위로 탐색할 수도 있습니다. 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;

참조 제한사항

참조 경로 및 이름에는 유효한 유니코드 문자를 어떤 순서로든 포함할 수 있지만 다음을 비롯하여 몇 가지 제한사항이 있습니다.

  1. reference.fullPath의 전체 길이는 UTF-8 인코딩 시 1~1,024바이트 사이여야 합니다.
  2. 캐리지 리턴 또는 라인 피드 문자는 사용할 수 없습니다.
  3. #, [, ], * 또는 ?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에 파일을 업로드하는 방법을 알아보세요.